JAVA-270 · Lesson 9 of 12 · 24 min
Domain modeling
▶ Video coming soon A video version of this lesson is on the way.
Tuesday, March 14, 2028. The hexagon from last week has a core in the middle, and tonight's question is what goes inside it. Ingrid opens with a story from the counter. Last Saturday a customer was told his bike was ready when it was not, because one screen treated a repair as done when the mechanic signed it off and another treated it as done when the customer had paid. Two people at the same shop used the same word for two different things, and the code had copied both. Domain modeling is the discipline of getting the words, the things and the rules of the business into the code clearly enough that this stops happening.
Ubiquitous language
Eric Evans's book Domain-Driven Design (2003) gave the field most of its vocabulary. His first idea is the ubiquitous language: a shared set of terms, agreed between the people who run the business and the people who write the software, used in conversation, in documents and in the code itself. If Odile says a repair is finished when the work is done and collected when the customer has picked it up and paid, then the code has a status FINISHED and a status COLLECTED, a method finish and a method collect, and nobody writes done.
Building the language is a conversation, not a document handed down. Hamza sat with Kofi, Tamsin and Odile for an hour and wrote down every word they used about repairs, then asked what each one meant. Several turned out to be two words in disguise, and two turned out to be the same thing under different names.
| Word heard at the counter | What it really meant | Term in the code |
|---|---|---|
| Done | Sometimes work finished, sometimes paid and picked up | FINISHED and COLLECTED, two states |
| Job, ticket, repair | The same thing | Repair |
| Quote | The price agreed before work starts | Quote, a value with a total and an expiry date |
| Customer, client, rider | The same person | Customer |
| Bike | Sometimes a customer's bike, sometimes a rental | CustomerBike and RentalBike |
| Part | A kind of part in the catalog, or one physical part on the shelf | Part (kind) and StockCount (how many) |
The model in the code should read like the shop talking. A method called markStatus3 says nothing; a method called collect says what happened at the counter. When the code and the conversation use the same words, a bug report from Kofi can be read straight against the code.
Entities and value objects
Evans's next distinction is between two kinds of object in a domain model. An entity has an identity that lasts while its attributes change. A repair is an entity: repair R-1042 is the same repair when its status moves from booked to finished, and two repairs for the same customer on the same day with the same description are still two different repairs. A value object has no identity of its own; it is defined entirely by its attributes, and two value objects with the same attributes are interchangeable. Money is a value object: one 25-dollar amount is as good as another. So are a date range, a part code and a quote.
Java records are an excellent fit for value objects. They are immutable, they compare by value with equals and hashCode written for you, and their compact constructor is a natural place to check that the value makes sense. An entity is usually a class with an identifier, and its equality is based on that identifier alone.
import java.util.*;
public class Main {
record Money(long cents) {
Money {
if (cents < 0) throw new IllegalArgumentException("money cannot be negative: " + cents);
}
Money plus(Money other) { return new Money(cents + other.cents); }
public String toString() { return String.format("%d.%02d", cents / 100, cents % 100); }
}
static final class Repair {
private final String id;
private String description;
private Money quote;
Repair(String id, String description, Money quote) { this.id = id; this.description = description; this.quote = quote; }
void requote(Money newQuote) { quote = newQuote; }
@Override public boolean equals(Object o) { return o instanceof Repair r && r.id.equals(id); }
@Override public int hashCode() { return id.hashCode(); }
public String toString() { return id + " " + description + " " + quote; }
}
public static void main(String[] args) {
Money a = new Money(2500), b = new Money(2500);
System.out.println("equal money: " + a.equals(b) + ", sum " + a.plus(b));
Repair r1 = new Repair("R-1042", "brake bleed", new Money(4500));
Repair same = new Repair("R-1042", "brake bleed", new Money(4500));
Repair twin = new Repair("R-1043", "brake bleed", new Money(4500));
System.out.println("same id: " + r1.equals(same) + ", twin: " + r1.equals(twin));
Set<Repair> open = new HashSet<>(List.of(r1));
r1.requote(new Money(5200));
System.out.println("still found after requote: " + open.contains(r1) + " -> " + r1);
try { new Money(-100); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); }
}
}equal money: true, sum 50.00 same id: true, twin: false still found after requote: true -> R-1042 brake bleed 52.00 money cannot be negative: -100
What this code does
Money is a record, so two amounts of 2500 cents are equal and adding them gives a new Money. Repair is an entity whose equals and hashCode use only its id, so a repair with a twin description is still a different repair, and changing the quote does not lose it from a HashSet. The compact constructor in Money refuses negative amounts, so an invalid amount can never exist.
The HashSet line matters more than it looks. If Repair's equals and hashCode used all its fields, changing the quote would change the hash code, and the set would no longer be able to find the repair it was holding. Entities hash on identity; values hash on everything, but values never change.
Make invalid states impossible
A rich domain model checks its rules where the data lives. A domain invariant is a rule that must always hold for an object to make sense: a date range ends after it starts, a quantity is positive, a part code has the shop's format. If the constructor enforces the invariant, every other piece of code can rely on it without checking again. Yaron Minsky's slogan for this, from the functional programming world, is to make illegal states unrepresentable.
The opposite habit is called primitive obsession: passing raw strings, ints and longs around for things that have rules. A method that takes three ints cannot stop someone passing the quantity where the price should go; a method that takes a Quantity and a Money can.
import java.time.*;
public class Main {
record PartCode(String value) {
PartCode {
if (!value.matches("[A-Z]+(-[A-Za-z0-9x]+)*")) throw new IllegalArgumentException("bad part code: " + value);
}
}
record Quantity(int value) {
Quantity { if (value <= 0) throw new IllegalArgumentException("quantity must be positive: " + value); }
}
record RentalPeriod(LocalDate from, LocalDate to) {
RentalPeriod {
if (!to.isAfter(from)) throw new IllegalArgumentException("rental must end after it starts: " + from + " to " + to);
}
long days() { return Duration.between(from.atStartOfDay(), to.atStartOfDay()).toDays(); }
}
static void attempt(String label, Runnable r) {
try { r.run(); System.out.println(label + ": ok"); }
catch (IllegalArgumentException e) { System.out.println(label + ": " + e.getMessage()); }
}
public static void main(String[] args) {
attempt("code TUBE-700x25", () -> new PartCode("TUBE-700x25"));
attempt("code tube 700", () -> new PartCode("tube 700"));
attempt("quantity 0", () -> new Quantity(0));
RentalPeriod week = new RentalPeriod(LocalDate.of(2028, 3, 18), LocalDate.of(2028, 3, 25));
System.out.println("rental days: " + week.days());
attempt("backwards rental", () -> new RentalPeriod(LocalDate.of(2028, 3, 25), LocalDate.of(2028, 3, 18)));
}
}code TUBE-700x25: ok code tube 700: bad part code: tube 700 quantity 0: quantity must be positive: 0 rental days: 7 backwards rental: rental must end after it starts: 2028-03-25 to 2028-03-18
What this code does
Each record's compact constructor enforces one invariant: part codes match the shop's pattern, quantities are positive and rental periods end after they start. Once an object exists, the rule holds, so code that receives a RentalPeriod never needs to check its dates again. The attempt helper runs each construction and prints either ok or the reason it was refused.
Domain types also make method signatures say more. Compare a method reserve(String, int, String, String) with reserve(PartCode, Quantity, RentalPeriod, Customer). The second cannot be called with its arguments in the wrong order, and anyone reading it knows what each one is.
Modeling states with sealed types
The repair that was called done twice is a state problem. Lesson 5 modeled states with a sealed interface; in a domain model the same idea lets each state carry exactly the data that makes sense in it. A booked repair has a promised date. A finished repair has the mechanic who signed it off. A collected repair has the amount paid. A plain class with all three fields, mostly null, would let code read the amount paid on a repair that has not been collected.
import java.time.*;
import java.util.*;
public class Main {
sealed interface RepairState permits Booked, Finished, Collected {}
record Booked(LocalDate promised) implements RepairState {}
record Finished(LocalDate promised, String signedOffBy) implements RepairState {}
record Collected(String signedOffBy, long paidCents) implements RepairState {}
static RepairState finish(RepairState s, String mechanic) {
return switch (s) {
case Booked b -> new Finished(b.promised(), mechanic);
case Finished f -> throw new IllegalStateException("already finished by " + f.signedOffBy());
case Collected c -> throw new IllegalStateException("already collected");
};
}
static RepairState collect(RepairState s, long paid) {
return switch (s) {
case Finished f -> new Collected(f.signedOffBy(), paid);
case Booked b -> throw new IllegalStateException("not finished yet, promised " + b.promised());
case Collected c -> throw new IllegalStateException("already collected");
};
}
static String readyMessage(RepairState s) {
return switch (s) {
case Booked b -> "Not ready; promised for " + b.promised();
case Finished f -> "Ready for pickup, checked by " + f.signedOffBy();
case Collected c -> "Picked up and paid";
};
}
public static void main(String[] args) {
RepairState s = new Booked(LocalDate.of(2028, 3, 16));
System.out.println(readyMessage(s));
try { collect(s, 4500); } catch (IllegalStateException e) { System.out.println("refused: " + e.getMessage()); }
s = finish(s, "Tamsin");
System.out.println(readyMessage(s));
s = collect(s, 4500);
System.out.println(readyMessage(s) + " " + s);
}
}Not ready; promised for 2028-03-16 refused: not finished yet, promised 2028-03-16 Ready for pickup, checked by Tamsin Picked up and paid Collected[signedOffBy=Tamsin, paidCents=4500]
What this code does
Each state is a record holding only the data that exists in that state, so there is no way to read an amount paid from a repair that has only been booked. The finish and collect functions are the only ways to move between states, and they refuse moves the shop does not allow, such as collecting a repair that is not finished. Because the interface is sealed, every switch must handle all three states or it will not compile.
With this model, Saturday's mistake cannot happen in the same way: the message the customer sees is computed from the state, and the only state that says ready is Finished. If Odile later adds a state such as WaitingForParts, the compiler will point to every switch that needs a new case.
Aggregates
Some rules span several objects. A rental booking at Second Gear has lines, one per bike or accessory, and the shop has a rule that one booking can hold at most four bikes, because that is how many fit on the van. If any piece of code could add lines to the list directly, the rule would have to be checked everywhere. Evans's answer is the aggregate: a cluster of objects treated as one unit for changes, with one entity, the aggregate root, as the only way in. Outside code holds a reference to the root and asks it to make changes; the root checks the rules.
import java.util.*;
public class Main {
record Line(String item, boolean isBike, long cents) {}
static final class RentalBooking {
static final int MAX_BIKES = 4;
private final String id;
private final List<Line> lines = new ArrayList<>();
RentalBooking(String id) { this.id = id; }
void add(Line line) {
long bikes = lines.stream().filter(Line::isBike).count();
if (line.isBike() && bikes == MAX_BIKES) throw new IllegalStateException(id + " already has " + MAX_BIKES + " bikes");
lines.add(line);
}
List<Line> lines() { return List.copyOf(lines); }
long total() { return lines.stream().mapToLong(Line::cents).sum(); }
}
public static void main(String[] args) {
RentalBooking b = new RentalBooking("B-207");
for (int i = 1; i <= 4; i++) b.add(new Line("hybrid " + i, true, 4000));
b.add(new Line("child seat", false, 800));
try { b.add(new Line("hybrid 5", true, 4000)); }
catch (IllegalStateException e) { System.out.println("refused: " + e.getMessage()); }
try { b.lines().add(new Line("sneaky bike", true, 0)); }
catch (UnsupportedOperationException e) { System.out.println("cannot change lines from outside"); }
System.out.println(b.lines().size() + " lines, total " + b.total());
}
}refused: B-207 already has 4 bikes cannot change lines from outside 5 lines, total 16800
What this code does
RentalBooking is the aggregate root: lines can only be added through its add method, which enforces the four-bike limit. The lines method hands out an unmodifiable copy, so outside code that tries to add a line directly gets an UnsupportedOperationException instead of breaking the rule. The final line shows five lines with a total of 16800 cents, four bikes and a child seat.
Evans gives a few rules of thumb for aggregates: keep them small, refer to other aggregates by identifier rather than by holding them, and save and load an aggregate as a whole. A booking holds a customer id, not a Customer object, so changing a customer's phone number never needs the booking.
Anemic and rich models
Martin Fowler named a common failure the anemic domain model: classes that are only bags of getters and setters, with all the rules in service classes elsewhere. The objects look like a model, but they cannot protect themselves, and every service must remember every rule. A rich domain model puts behavior and rules on the objects they belong to: Money adds, RentalPeriod counts days, RentalBooking refuses a fifth bike. The use cases from the hexagon then become short: load the aggregate, ask it to do something, save it.
Not everything belongs on an entity. A rule that involves several aggregates, such as working out whether a part is low across all three stockrooms, may live in a domain service, a stateless object in the core named in the ubiquitous language. The test is whether the operation naturally belongs to one thing. Adding a bike belongs to a booking; comparing stock across rooms does not belong to any one room.
| Concept | Identity | Changes? | Java form at Second Gear |
|---|---|---|---|
| Entity | Yes, by id | Attributes change over time | Repair, Customer, RentalBooking |
| Value object | No | Never; make a new one | Money, PartCode, Quantity, RentalPeriod as records |
| Aggregate | Through its root | Only through the root | RentalBooking with its Lines |
| Domain service | No | Stateless | StockAcrossRooms |
| State type | No | Replaced on each transition | Sealed RepairState with three records |
Try it yourself
Write a value object
The starter passes a discount rate, a whole number from 0 to 100, around as a raw int, and nothing stops 140. Write a record Rate with a compact constructor that rejects values below 0 or above 100 with an IllegalArgumentException whose message is rate out of range: N, and a method of(long cents) that returns that share of an amount, rounded down.
The program should print discount on 4500: 675 and then rate out of range: 140.
public class Main {
static long share(int rate, long cents) { return cents * rate / 100; }
public static void main(String[] args) {
System.out.println("discount on 4500: " + share(15, 4500));
System.out.println("discount on 4500: " + share(140, 4500));
}
}Try it yourself
Guard an aggregate
The starter lets anyone add lines to a repair's parts list, so a repair can end up with more than three of the same part, which the shop never allows without a manager. Make the list private, add a method use(String code) on RepairParts that refuses a fourth copy of the same code with an IllegalStateException too many CODE, and a method count(String code).
The program should print refused: too many PAD-DISC and then PAD-DISC x3.
import java.util.*;
public class Main {
static final class RepairParts {
final List<String> codes = new ArrayList<>();
}
public static void main(String[] args) {
RepairParts p = new RepairParts();
for (int i = 0; i < 4; i++) p.codes.add("PAD-DISC");
System.out.println("PAD-DISC x" + Collections.frequency(p.codes, "PAD-DISC"));
}
}Common mistakes
MistakeLetting one word mean two things in the code.
InsteadAgree a ubiquitous language and split ambiguous words into separate terms.
MistakeWriting equals on an entity using all its fields.
InsteadBase an entity's equality on its id; base a value object's on all its fields.
MistakePassing raw strings and ints for things with rules.
InsteadWrap them in small records that check their invariants.
MistakePutting every rule in service classes over plain getters and setters.
InsteadPut behavior and rules on the objects they belong to.
MistakeHanding out a modifiable list from inside an aggregate.
InsteadChange an aggregate only through its root and return unmodifiable copies.
Summary and key terms
- Domain modeling puts the business's words, things and rules into the code.
- Eric Evans's Domain-Driven Design gives the vocabulary.
- A ubiquitous language is a set of terms shared by the business and the code, and it splits ambiguous words such as done into separate terms.
- Entities have an identity that lasts while their attributes change, so their equality uses their id.
- Value objects are defined by their attributes, never change and fit Java records well.
- Domain invariants belong in constructors, so invalid objects cannot exist; wrapping primitives in small types avoids primitive obsession.
- Sealed types model states that each carry only their own data.
- An aggregate is a cluster of objects changed only through its root, which enforces rules spanning the cluster.
- A rich domain model puts behavior on its objects; an anemic one leaves them as data bags.
- Domain services hold operations that belong to no single object.
- Domain model
- The part of a program that represents the business's concepts and rules.
- Domain-Driven Design
- Eric Evans's approach to software design centered on the business domain, from his 2003 book.
- Ubiquitous language
- A shared set of terms used by both the business and the code.
- Entity
- An object with an identity that lasts while its attributes change.
- Value object
- An object defined entirely by its attributes, with no identity of its own.
- Domain invariant
- A rule that must always hold for an object to make sense.
- Primitive obsession
- Using raw strings and numbers for concepts that have rules.
- Aggregate
- A cluster of objects treated as one unit for changes.
- Aggregate root
- The one entity through which an aggregate is changed.
- Anemic domain model
- A model whose classes hold data but no behavior, leaving rules elsewhere.
- Rich domain model
- A model whose objects carry the behavior and rules that belong to them.
- Domain service
- A stateless operation in the core that belongs to no single entity or value.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Is a part code an entity or a value object?
Show answer
A value object: two equal codes are interchangeable.
Why should Repair's equals use only its id?
Show answer
Its other fields change; identity does not, so hashing stays stable.
Where should the rule that a rental ends after it starts be checked?
Show answer
In the RentalPeriod constructor.
What problem does a sealed RepairState solve?
Show answer
Each state holds only its own data, and switches must cover all states.
Why does RentalBooking return List.copyOf(lines)?
Show answer
So outside code cannot add lines and bypass the four-bike rule.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.