I keep seeing the same DDD mistake: an “anemic” Order entity whose rules are scattered across many service classes. An aggregate solves this: there is exactly one root, in this case the Order. Only this root is allowed to change the internal state, so all invariants are checked in one place. In our Order service, the context is simple: an Order must never exceed the credit limit. In addition, no line items may be added after it has been submitted. In the example below, we pull both rules into the aggregate root. This way, no caller – whether a REST controller or an agent-driven workflow – can bypass these rules. It also keeps transactions small: one aggregate corresponds to exactly one transaction, and other aggregates are referenced only via their IDs.
public class Order { private final OrderId id; private final List<OrderLine> lines = new ArrayList<>(); private OrderStatus status = OrderStatus.DRAFT; public void addLine(ProductId product, int qty, Money price) { if (status != OrderStatus.DRAFT) throw new IllegalStateException("Order already submitted"); lines.add(new OrderLine(product, qty, price)); } public void submit(Money creditLimit) { if (total().isGreaterThan(creditLimit)) throw new IllegalStateException("Credit limit exceeded"); status = OrderStatus.SUBMITTED; } private Money total() { /* sum of qty * price */ }}

Schreibe einen Kommentar