In Domain-Driven Design (DDD), an aggregate is a small group of objects that is always changed and saved as one unit, and only one object, the aggregate root, is visible to the outside. The root checks the business rules (called invariants), so no other code can put the data into an invalid state. In our example context, an online shop has the rule „an order may contain at most 10 items“, and the Order class is the root that guards this rule. The code below shows that callers can only use addItem and never touch the internal list directly, so the rule cannot be bypassed. Keep aggregates small and refer to other aggregates only by id (here customerId), because this keeps transactions short and the consistency boundary clear.

public class Order { // aggregate root
private static final int MAX_ITEMS = 10;
private final OrderId id;
private final CustomerId customerId; // other aggregate: id only
private final List<OrderItem> items = new ArrayList<>();
public Order(OrderId id, CustomerId customerId) {
this.id = id;
this.customerId = customerId;
}
public void addItem(ProductId product, int quantity) {
if (items.size() >= MAX_ITEMS) {
throw new IllegalStateException("An order has max " + MAX_ITEMS + " items");
}
items.add(new OrderItem(product, quantity));
}
public List<OrderItem> items() {
return List.copyOf(items); // read-only view
}
}

Kommentar verfassen

I’m Iman

Mein Name ist Iman Dabbaghi. Ich arbeite als Senior Software Engineer in der Schweiz. Außerdem interessiere ich mich sehr für gewaltfreie Kommunikation, Bachata-Tanz und Musik sowie fürs die Persönlichkeitsentwicklung.

Ich habe einen Masterabschluss in Informatik von der Universität Freiburg in Deutschland, bin Spring/Java Certified Professional (OCP), Certified Professional for Software Architecture (CPSA-F) und ein lebenslanger Lernender 🎓.

EN:

My name is Iman Dabbaghi. I work as a Senior Software Engineer in Switzerland. I am also very interessted in nonviolent communication, Bachata dance and music and also for personal development.

I hold a masters degree in computer science from the university of Freiburg in Germany, am a Spring / Java Certified Professional (OCP), Certified Software Architecture (CPSA-F) and Life Long Learner🎓

Let’s connect