Question

Taking some ideeas regarding validation from this book , is it really a good practice and proper SoC to put data validation inside domain objects? There he gives example about validating addresses, checking if it is between an interval of chars long, adding a pattern etc. When thinking about validation isn't better to put the validation right when the user asks something from the application , for example in a command object (cqrs) and stop the user if the command is invalid? Also another problem comes with internationalisation , how would handle the patterns for different alphabets? Also another problem comes with duplicate checks, what if the domain objects checks for each invariant of the property (when it can be of mixed type) but the command actually assumes only one single invariatn to be valid ?

Why I am confused is because Eric Evans forewards this book written by Vernon , but i find some design styles innapropriate . So is it better to validate properties format (string lenght, string format etc, like that address example) in the domain or outside the domain ?

Was it helpful?

Solution

There is user input validation (usually input format) and business rules. The input validation makes sense to be done at the entry point (usually a controller and depending on a framework it can be automatically done), there's no benefit in sending invalid data forward for processing.

However, the domain contains most of the input validation rules so it seems you have to choose between keeping the rules inside the Domain or repeating yourself. But you don't have to, because the input validation can be easily encapsulated into value objects (VO) so they are part of the domain but you can still use them outside the domain to validate the input.

That's why it's best to use VO as much as possible , they usually are domain concepts AND they ensure the value is valid. The entity using them simply must refuse a null value.

I don't how you can validate a command, at most you can check if the user or context can create and send that command, but the command itself is just a semantic DTO with the relevant parameters. It's up to the command handler to decide how valid the command is. Also, I don't think a command should assume anything, it' about what to do not, how to do it.

About i18n, IMO the validator must be aware of the current culture so a possible solution is a service which return the pattern for the current culture. This means the validator (I usually implement it as a static method of the VO) will take something like IKnowValidationPatterns as a dependency.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top