Video in progress
What is an anemic domain model, and when does it become a problem?
It is a model where entities consist only of fields and getters/setters, and all the business logic lives in service classes. It is fine in plain CRUD, but as the rules multiply, invariants get scattered and it becomes easy to put an object into an invalid state.
📖 Answer
The anemic version:
order.setStatus(Status.PAID);
order.setPaidAt(Instant.now());
order.setPaidAmount(amount);
These three lines get repeated in PaymentService, AdminController and RefundJob. In one place setPaidAt was forgotten, and now there are orders in the DB with PAID but paid_at = null. Or a cancelled order slips into the paid state, because nobody checked.
The rich model:
public void markPaid(Money amount, Clock clock) {
if (status != Status.AWAITING_PAYMENT)
throw new IllegalStateException("To'lab bo'lmaydi: " + status);
if (!amount.equals(total))
throw new IllegalArgumentException("Summa mos emas");
this.status = Status.PAID;
this.paidAt = Instant.now(clock);
this.paidAmount = amount;
}
Now the rule is in one place and there is no way around it, since there are no setters.
When an anemic model is fine:
- the application mostly stores and displays data and has almost no rules;
- the objects are DTOs, request/response models.
When it is a problem:
- the same checks are repeated in several services;
- bugs show up as "records in an invalid state";
- service classes have grown past 1000 lines.
Services stay anyway: they manage transactions, repositories and external calls, but they hand the decision to the object itself.
Sign up to mark studied questions and save your progress.