Design patterns·topic 7 of 10
Modelling the domain
The words a team uses when it stops arguing about frameworks and starts arguing about what an order actually is. These are the pieces a domain model is built from and the failure it decays into.
Read in order · tick what you already know
- 01
the rule about when an order can be cancelled lives on the order, and there is exactly one copy of it.
Domain model
- 02
the objects have only fields and accessors, and every rule about them lives in a class ending in Service.
Anaemic domain model
- 03
two of them with identical fields are still different things, because the thing that makes them the same is the id.
Entity
- 04
two of them with the same contents are interchangeable, so you never update one — you replace it.
Value object
- 05
the two ids were both strings, you passed them in the wrong order, and nothing complained until production.
Tiny type
- 06
you could not construct an invalid one, so nothing downstream had to check whether it was valid.
Always-valid domain model
- 07
you can change these five objects together in one transaction, and anything outside them has to wait its turn.
Aggregate
- 08
outside code holds a reference to the order and never to a line item, so every change goes through the order.
Aggregate root
- 09
creating a valid aggregate needed four objects and a rule, so a separate object does it and the constructor stayed private.
Domain factory
- 10
the rule for what counts as a lapsed customer is one object, used both to filter the query and to check one in memory.
Specification pattern
- 11
the model recorded that the order was placed as a thing that happened, and three unrelated reactions followed.
Domain event
- 12
there is one method per use case, it opens the transaction, calls the model, and contains no business rules itself.
Service layer
- 13
it fetches the aggregate, calls one method on it, saves it, and that is the entire body of the method.
Application service
- 14
the operation genuinely belonged to no single object — it needed two of them — so it became an object of its own.
Domain service
- 15
the object crossing the boundary has fields matching the screen, not the model, and no behaviour at all.
Data transfer object
- 16
one class exists purely to turn the domain object into the response shape, and neither of them knows about the other.
Assembler