Domain entity validation code inside or outside the object?
Where would you place validation code fo开发者_Python百科r 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?
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
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.
精彩评论