Domain modelling in Java
Entities, value objects, aggregates, invariants, and the anaemic model that pushes every rule into a service.
Most backend code is a Service that loads rows into objects with getters and setters, applies the rules in the service, and saves the objects back. It works, and it is why the rules of a business end up spread across forty service methods, duplicated, and impossible to find. Domain modelling is the discipline of putting the rules in the objects that the rules are about, so that an Order cannot be in a state the business says is impossible, whatever any service does to it. This lesson is the vocabulary and the Java shapes for it — and the honest costs, because a model that is richer than its domain is a different kind of mess.
Entities and value objects
An entity is something with an identity that persists through change: an order is the same order after its status changes, a customer is the same customer after a name change. Two entities are equal when their ids are equal. A value object is something defined entirely by its attributes: a Money of 500 paise in INR is interchangeable with any other 500 paise in INR, a postal address is its lines, a date range is its two dates. Two value objects are equal when their attributes are equal, and they are immutable — you do not change a Money, you compute a new one.
record Money(long paise, Currency currency) {
Money {
if (paise < 0) throw new IllegalArgumentException("negative money");
Objects.requireNonNull(currency);
}
Money plus(Money other) {
if (!currency.equals(other.currency)) throw new IllegalArgumentException("currency mismatch");
return new Money(paise + other.paise, currency);
}
static Money zero(Currency c) { return new Money(0, c); }
}Records are Java's value objects: immutable, equal by attributes, with a compact constructor for the validation. The clean-code lesson's primitive obsession is this lesson's motivation — charge(Money amount, CustomerId to) cannot swap its arguments, long amount, long customerId can — and the JPA course's equals/hashCode lesson is the entity half: an entity's equality is its id, and a record is the wrong shape for one.
Aggregates and invariants
An invariant is a rule that must hold at every moment the outside world can observe: an order's total equals the sum of its lines; a paid order has a payment reference; a shipped order cannot gain lines. An aggregate is the cluster of objects that must be changed together to keep those invariants — the order and its lines — with one entity as the root through which every change passes:
class Order {
private final OrderId id;
private final List<Line> lines = new ArrayList<>();
private Status status = Status.OPEN;
void addLine(Sku sku, int qty, Money unitPrice) {
if (status != Status.OPEN) throw new IllegalStateException("order " + id + " is " + status);
if (qty <= 0) throw new IllegalArgumentException("qty");
lines.add(new Line(sku, qty, unitPrice));
}
Money total() { return lines.stream().map(Line::subtotal).reduce(Money.zero(INR), Money::plus); }
void markPaid(PaymentRef ref) {
if (status != Status.OPEN) throw new IllegalStateException(...);
if (lines.isEmpty()) throw new IllegalStateException("nothing to pay for");
this.payment = ref; this.status = Status.PAID;
}
List<Line> lines() { return List.copyOf(lines); } // a copy: nobody adds a line around the rule
}Three properties make it an aggregate rather than a class with methods. Every change goes through the root — there is no getLines().add(...), because that would add a line to a shipped order; the getter returns a copy. The invariants are checked inside, so they hold whatever the caller intended. And the aggregate is the transaction boundary: one aggregate is loaded, changed, and saved in one transaction, and a rule that spans two aggregates (this customer may not have two open orders) is not an invariant of either — it is a policy checked by a service, eventually consistent, and the saga lesson's territory when it spans services.
Keep aggregates small. An Order that holds the customer, the customer's other orders and the products is one huge object loaded for every change, locked against every concurrent change, and the thing the JPA course's N+1 lesson warns about. Reference other aggregates by id (CustomerId), never by object.
The anaemic model, and why it is the default
An anaemic model is entities with fields and accessors and no behaviour; every rule lives in a service that reads the fields, decides, and writes them back:
// anaemic: the rule is in the service, and in the other six services that also change status
if (order.getStatus() == OPEN && !order.getLines().isEmpty()) { order.setStatus(PAID); order.setPaymentRef(ref); }It is the default for a reason: JPA wants a no-arg constructor and setters, Jackson wants the same, the tutorial did it, and it is fast to write. Its cost arrives later — the same rule written in four services with three variations, an Order set to PAID with no lines by a batch job nobody tested, and the question "can an order be cancelled after shipping?" answered by reading every service rather than one class. The rich model above answers it in cancel().
The reconciliation with the frameworks: keep the JPA entity's setters package-private or absent (Hibernate uses field access and needs no setters; a protected no-arg constructor satisfies it), map DTOs at the edge (the REST course), and let the aggregate be the JPA entity when the two shapes agree — which for most services they do — or keep a separate persistence model when they do not, at the cost of mapping code. The SOLID lesson's warning applies: a model richer than the domain is speculative generality; a Status enum with a transitionTo method and a service that checks the rest is a fine middle for a small domain.
Ubiquitous language
The names in the code are the names the business uses, exactly. If the sales team says "quote" and the code says PreOrder, every conversation translates and every translation loses something; if the code says Quote with a method accept() that produces an Order, a product owner can read the class. The test: a domain expert can follow the aggregate's public methods as a description of the process. Where the language is ambiguous — "customer" meaning both the buyer and the account — that is a bounded context boundary, the microservices course's term, and the two meanings get two models rather than one class with a mode flag.
Under the hood: how breaking the equals/hashCode contract corrupts a HashMap
An entity's identity is its id, which is exactly why the JPA course tells you to base equals/hashCode on it rather than on the mutable fields this lesson's Order carries. The reason is not stylistic — it is that HashMap and HashSet are built directly on top of the contract, and violating it does not throw an exception. It silently loses data.
HashMap.put and .get both start the same way: call hashCode() on the key, spread the bits (h ^ (h >>> 16), since Java 8, to mix the high bits into the low ones the table actually indexes with), then mask against the table size to pick a bucket. Only inside that bucket does equals() get a chance to run, to tell two keys with the same bucket apart. The contract — equal objects must return equal hash codes — exists because get only ever compares equals() against entries in the one bucket that hashCode() pointed it to. If an object's hash code can change after it is stored, get computes a different bucket for the "same" (by equals) object, looks there, finds nothing, and reports it missing — even though the original entry is still sitting, unreachable, in its original bucket.
That is the mechanism behind a real, common bug class: give an entity a mutable field, include that field in hashCode(), put the entity in a HashSet or use it as a HashMap key, then mutate the field. The object is now lost to every lookup that isn't a full iteration — not corrupted data exactly, but data the map can no longer find, which in production looks identical to data that vanished.
Try it yourself
Predict what mutation does to lookup
class Point {
int x;
Point(int x) { this.x = x; }
@Override public boolean equals(Object o) {
return o instanceof Point && ((Point) o).x == x;
}
@Override public int hashCode() { return x; }
}
Set<Point> set = new HashSet<>();
Point p = new Point(1);
set.add(p);
System.out.println("contains before mutation: " + set.contains(p));
p.x = 2;
System.out.println("contains after mutation: " + set.contains(p));p is still the exact same object reference both times contains is called — nothing removed it from the set. Using the bucket mechanism above, why does contains report false after the mutation?
The object never moved buckets — but the lookup now asks a different bucket for it
set.add(p) computed hashCode() when x was 1 and stored p in the bucket for that hash. Mutating p.x to 2 does not move the object — HashSet has no way to know a field it hashed on has changed, so p stays in the bucket for hash 1 forever. But the second contains(p) call recomputes hashCode() fresh, sees x == 2, and looks in the bucket for hash 2 — a different bucket, where p was never stored. The entry is not gone; it is simply unreachable from any lookup that recomputes the (now different) hash, which is every lookup. This is exactly the "lost entry" failure the contract exists to prevent, reproduced in five lines.
Misconceptions
- "Two unequal objects must have different hash codes, or something is broken." Backwards. The contract requires the opposite direction only: equal objects must share a hash code; unequal objects may share one too (a collision), and
HashMaphandles that correctly viaequals()inside the bucket. Chasing zero collisions is a performance micro-optimisation at best — since Java 8 a bucket that grows past a threshold treeifies into a balanced tree instead of a linked chain, so even heavy collision is degraded performance, not incorrect behaviour. What is never allowed to happen is equal objects with different hashes. - "Overriding
equals()withouthashCode()mostly breaks tests, not production." It breaks anySet/Mapusage silently, with no exception anywhere.Object's defaulthashCode()is identity-based (unrelated to yourequals()), so two objects yourequals()says are the same will, by default, land in different buckets and never be found as duplicates —contains, deduplication and cache lookups all fail quietly, which is worse than a test failure because nothing points at the cause.
Sources
- Joshua Bloch, Effective Java (3rd ed.) — Item 10 ("Obey the general contract when overriding equals") and Item 11 ("Always override hashCode when you override equals").
java.lang.ObjectJavadoc — the formalequals/hashCodecontract.- Eric Evans, Domain-Driven Design — entities, value objects and aggregates as this lesson uses the terms.