๐๐๐ถ๐น๐ฑ๐ถ๐ป๐ด ๐ฅ๐ถ๐ฐ๐ต ๐๐ป๐๐ถ๐๐ถ๐ฒ๐ ๐ถ๐ป ๐๐๐
Many developers treat entities as table rows. They create classes with only getters and setters. This is an Anemic Model.
An Anemic Model is a bag of data. It has no behavior. You put business rules in controllers or services.
This creates problems. You repeat validation in multiple places. Logic gets lost. Your code becomes a Big Ball of Mud. It is hard to change.
Domain-Driven Design (DDD) solves this. A Rich Entity has its own identity. It uses a unique ID. This ID stays the same when data changes.
Rich Entities hold data and business rules. This protects your object.
Stop using public setters. Do not let your system change data directly. Use named methods.
Example: Do not use: student.email = "new@email.com" Use: student.changeEmail("new@email.com")
The changeEmail method validates the input. It handles the audit log. The rules stay inside the entity.
Follow these five steps to fix an Anemic Model:
- Remove all public setters.
- Identify business reasons for changes.
- Create public methods with business verbs.
- Move logic from services to these methods.
- Use a constructor to require minimum valid data.
Your classes must express your business. They are not lists of database columns.
Start small. Remove one setter today. Create one business method. You will see fewer bugs. Your tests will be clearer.