Where would you place validation code for a domain entity? Inside the class itself in a method like Validate() or outside in the context where the object is being used? Or both?
A:
With a recent project we had a mixture of the two. For simple data constraints like field length, or regular expresssions we would have the validations on the entity. For more complex validations (like relationships with other entities in the system), we would use a seperate service that validated the entity and we found that this worked very well.
Furis
2010-01-12 06:40:27
A:
If the validation only has to consult objects inside the entity then put the validation inside the entity. For a Person entity
- Checking if age > 0 or name is not empty should be within the entity in a validate() method
- Checking if a course is covered by a certain policy (from a list of all policies) will involve quering/reading other course/policy objects which may be not related to the entity itself and should be done by a context/service/validator outside the entity
Calm Storm
2010-03-17 13:02:37