Here is my technical diary of the last week of 2015.
Domain Driven Design, Application Layers and Validation
I read a post of Mathias Verreas about the different layers of an application and what kind of validations reside in each one (http://verraes.net/2015/02/form-command-model-validation). His ideas join what I previously wrote about java.validation (https://erichonorez.wordpress.com/2015/12/20/history-log-of-my-week-512015/).
It is sometimes tempting to use an unified validation model across all architecture layers in order to ensure state consistency. This temptation could comes because you want to avoid some kind of duplication in your validation or just because the form filled by the user will impact a specific entity. So the entities are used as model to validate user input in a form (presentation layer), used to validate command (application layer) and business rules (domain layer).
However with that kind of unified model you may break the Single Responsibility Principle. Your domain model is poluated by responsibilities of layers above. Validations become hard to maintain and evolve because of the complexity and fragility. Even more if it is a multi tenant application and tenant specific rules are also in this unified model.
Validation in these different layers have different goals. Of course if a form field is required because in will fill a property of an entity your will have some kind of duplication because this field will be required in the several layers. But models used in a form are used to validate the format of user input and help the user to correct his mistakes.
Validations in he domain model ensure that the model never goes in a invalid state. It is a serious problem if some invariants of your domain layer are not respected. When these severe situations happen exceptions should be thrown and the goal is to not help the user the correct what he did.
Some rules in the UI could be more restrictive. The illustrate the fact that rules applied at the several layers have different goals just imagine the case of an accountable application. In your domain model a transaction could have an optional communication field. However for a specific client this field should be required. So instead of modifying your domain model you could just move this requirement at the application or UI layer. If some clients have specific requirements on their business model it should not impact your domain model.
In a multi tenant application it is really important that your domain is to help tenants in their domain so your domain is different of your client’s domain. If some client have specific requirements the should be moved as far as possible at the boundaries of your system.