Aggregates and invariants
On This Lesson 4 topics
This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.
In this lesson
design aggregates around the rules they protect.
Planned topics
- An invariant is a rule that must always hold, such as "order total equals the sum of its lines".
- An aggregate is a cluster of objects changed as one unit, with a root (
Order) as the only entry point. - Keep aggregates small; one transaction changes one aggregate.
- Reference other aggregates by ID, not by object reference (
CustomerId, notCustomer). - Design around invariants, not around tables. Rules across aggregates are eventually consistent (MID-030).
Draft outline details
Demonstration
public class Order { // aggregate root
private final OrderId id;
private final CustomerId customerId; // by ID
private final List<OrderLine> lines = new ArrayList<>();
private Status status = Status.NEW;
public void addLine(ProductId p, int qty, Money price) {
if (status != Status.NEW) throw new IllegalStateException("order not editable");
lines.add(new OrderLine(p, qty, price));
}
}Check your understanding
How should Order refer to its customer?
Show answer
By CustomerId.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.