Lesson 3 of the DDD course · Invariants, transition functions, and reference-by-identity · ~30 minutes
One entity plus its tightly-bound parts, guarded by functions. This is the pattern most of Meridian's business logic will live in.
Meridian rules, straight from the business:
total must equal the sum of its lines.draft.In a typical codebase, those rules end up scattered: one check in the HTTP handler, another in the checkout component, a third in a database trigger, none in the type. Then a new code path — the admin tool, the import job — forgets one. This is the anemic domain model: types that carry data while the rules live everywhere and nowhere.[Fowler]
An aggregate is a
cluster of entities and value objects treated as a single unit, with one entry point — the
root. Its defining promise: the rules inside the boundary are true
instantly, after every change.[Evans; Fowler]
Meridian's order aggregate: the Order root plus its OrderLines
(Email, Cents, Quantity ride along inside lines).
The functional translation of that promise is beautifully small:
interface Order {
readonly id: OrderId;
readonly customerId: CustomerId;
readonly status: OrderStatus;
readonly lines: readonly OrderLine[];
readonly total: Cents; // invariant: always equals Σ qty × unitPrice
}
export function addLine(order: Order, line: OrderLine): Result<Order, OrderError> {
if (order.status !== "draft")
return { ok: false, error: "order not editable" };
if (!Number.isInteger(line.qty) || line.qty <= 0)
return { ok: false, error: "quantity must be a positive whole number" };
if (order.lines.some(l => l.product === line.product))
return { ok: false, error: "duplicate product line" };
const lines = [...order.lines, line];
const total = lines.reduce((s, l) => s + l.qty * l.unitPrice, 0);
return { ok: true, value: { ...order, lines, total } };
}
Read the signature — it is the design document: “give me an order and a line; you'll get back either a valid new order or a named reason”. Every caller, current and future, inherits the rules. The total can never drift, because the only function that touches lines recomputes it.
The order holds customerId — a branded id, not a Customer
object. Why:
addLine calls to the same order — last writer wins, so
the shell retries or rejects (Lesson 8). (3) If you find “handlers” reaching into
order.lines directly, the transition module is leaking — fix the export list.
Implement addLine with all four business rules. Tests reject every illegal path
and verify the recomputed total.
The aggregate guards what's true right now. But “draft → placed → shipped” is a
lifecycle, and modeling it with a status string keeps illegal stages representable.
Next lesson: make illegal states unrepresentable — each stage becomes its own
type, and the compiler refuses to ship a draft.