Lesson 7: Rich domain modeling
When all business logic sits in services and classes hold only data with public getters and setters, any line of code can break the rules: a negative total, an order with no items. In this lesson we move behavior onto the entity itself, so an invalid state simply cannot be created.
A rich domain model is like a vending machine: you cannot open the door and grab a can — you insert a coin, and the machine dispenses by its own rules.
- Rich domain model
- Business behavior and rules live inside the entity itself: private fields, with every state change passing through a rule-checking method.
- anemic model
- Data-only classes with public getters/setters while all logic sits in services — any caller can bypass the rules and create invalid state.
- invariant
- A rule that must always hold for the object — e.g. an order total is never negative. In a rich model the entity enforces it itself.