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

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