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