title: Domain Validation in a CQRS architecture
body: <p><em>Danger ... Danger Dr. Smith... Philosophical post ahead</em></p>
  
  <p>The purpose of this post is to determine if placing the validation logic outside of my domain entities (aggregate root actually) is actually granting me more flexibility or it's <em>kamikaze code</em></p>
  
  <p>Basically I want to know if there is a better way to validate my domain entities. This is how I am planning to do it but I would like your opinion</p>
  
  <p>The first approach I considered was:</p>
  
  <pre><code>class Customer : EntityBase&lt;Customer&gt;
  {
     public void ChangeEmail(string email)
     {
        if(string.IsNullOrWhitespace(email))   throw new DomainException(“...”);
        if(!email.IsEmail())  throw new DomainException();
        if(email.Contains(“@mailinator.com”))  throw new DomainException();
     }
  }
  </code></pre>
  
  <p>I actually do not like this validation because even when I am encapsulating the validation logic in the correct entity, this is violating the Open/Close principle (Open for extension but Close for modification) and I have found that violating this principle, code maintenance becomes a real pain when the application grows up in complexity. Why? Because domain rules change more often than we would like to admit, and if the rules are <strong>hidden and embedded</strong> in an entity like this, they are hard to test, hard to read, hard to maintain but the real reason why I do not like this approach is: if the validation rules change, I have to come and edit my domain entity. This has been a really simple example but in RL the validation could be more complex</p>
  
  <p>So following the philosophy of Udi Dahan, <strong>making roles explicit</strong>, and the recommendation from Eric Evans in the blue book, the next try was to implement the specification pattern, something like this</p>
  
  <pre><code>class EmailDomainIsAllowedSpecification : IDomainSpecification&lt;Customer&gt;
  {
     private INotAllowedEmailDomainsResolver invalidEmailDomainsResolver;
     public bool IsSatisfiedBy(Customer customer)
     {
        return !this.invalidEmailDomainsResolver.GetInvalidEmailDomains().Contains(customer.Email);
     }
  }
  </code></pre>
  
  <p>But then I realize that in order to follow this approach I had to mutate my entities first in order to pass the <em>value being valdiated</em>, in this case the email, but mutating them would cause  my domain events being fired which I wouldn’t like to happen until the new email is valid</p>
  
  <p><strong>So after considering these approaches, I came out with this one, since I am going to implement a CQRS architecture:</strong></p>
  
  <pre><code>class EmailDomainIsAllowedValidator : IDomainInvariantValidator&lt;Customer, ChangeEmailCommand&gt;
  {
     public void IsValid(Customer entity, ChangeEmailCommand command)
     {
        if(!command.Email.HasValidDomain())  throw new DomainException(“...”);
     }
  }
  </code></pre>
  
  <p>Well that’s the main idea, the entity is passed to the validator in case we need some value from the entity to perform the validation, the command contains the data coming from the user and since the validators are considered <strong>injectable</strong> objects they could have external dependencies injected if the validation requires it.</p>
  
  <p><strong>Now the dilemma</strong>, I am happy with a design like this because my validation is encapsulated in individual objects which brings many advantages: easy unit test, easy to maintain, domain invariants are explicitly expressed using the Ubiquitous Language, easy to extend, validation logic is centralized and validators can be used together to enforce complex domain rules. And even when I know  I am placing the validation of my entities outside of them (You could argue a code smell - Anemic Domain) but I think the trade-off is acceptable</p>
  
  <p>But there is one thing that I have not figured out how to implement it in a clean way. <em>How should I use this components...</em></p>
  
  <p>Since they will be injected, they won’t fit naturally inside my domain entities, so basically I see two options:</p>
  
  <ol>
  <li><p>Pass the validators to each method of my entity</p></li>
  <li><p>Validate my objects externally (from the command handler)</p></li>
  </ol>
  
  <p>I am not happy with the option 1 so I would explain how I would do it with the option 2</p>
  
  <pre><code>class ChangeEmailCommandHandler : ICommandHandler&lt;ChangeEmailCommand&gt;
  {
     // here I would get the validators required for this command injected
     private IEnumerable&lt;IDomainInvariantValidator&gt; validators;
     public void Execute(ChangeEmailCommand command)
     {
        using (var t = this.unitOfWork.BeginTransaction())
        {
           var customer = this.unitOfWork.Get&lt;Customer&gt;(command.CustomerId);
           // here I would validate them, something like this
           this.validators.ForEach(x =. x.IsValid(customer, command));
           // here I know the command is valid
           // the call to ChangeEmail will fire domain events as needed
           customer.ChangeEmail(command.Email);
           t.Commit();
        }
     }
  }
  </code></pre>
  
  <p>Well this is it. Can you give me your thoughts about this or share your experiences with Domain entities validation</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>I think it is not clear from my question, but the real problem is: Hiding the domain rules has serious implications in the future maintainability of the application, and also domain rules change often during the life-cycle of the app. Hence implementing them with this in mind would let us extend them easily. Now imagine in the future a rules engine is implemented, if the rules are encapsulated outside of the domain entities, this change would be easier to implement</p>
  
  <p>I am aware that placing the validation outside of my entities breaks the encapsulation as @jgauffin mentioned in his answer, but I think that the benefits of placing the validation in individual objects is much more substantial than just keeping the encapsulation of an entity. Now I think the encapsulation makes more sense in a traditional n-tier architecture because the entities were used in several places of the domain layer, but in a CQRS architecture, when a command arrives, there will be  a command handler accessing an aggregate root and performing operations against the aggregate root only creating a perfect window to place the validation.</p>
  
  <p>I'd like to make a small comparison between the advantages to place validation inside an entity vs placing it in individual objects</p>
  
  <ul>
  <li><p>Validation in Individual objects</p>
  
  <ul>
  <li>Pro. Easy to write</li>
  <li>Pro. Easy to test</li>
  <li>Pro. It's explicitly expressed</li>
  <li>Pro. It becomes part of the Domain design, expressed with the current Ubiquitous Language</li>
  <li>Pro. Since it's now part of the design, it can be modeled using UML diagrams</li>
  <li>Pro. Extremely easy to maintain</li>
  <li>Pro. Makes my entities and the validation logic loosely coupled</li>
  <li>Pro. Easy to extend</li>
  <li>Pro. Following the SRP</li>
  <li>Pro. Following the Open/Close principle</li>
  <li>Pro. Not breaking the law of Demeter (mmm)?</li>
  <li>Pro. I'is centralized</li>
  <li>Pro. It could be reusable</li>
  <li>Pro. If required, external dependencies can be easily injected</li>
  <li>Pro. If using a plug-in model, new validators can be added just by dropping the new assemblies without the need to re-compile the whole application</li>
  <li>Pro. Implementing a rules engine would be easier</li>
  <li>Con. Breaking encapsulation</li>
  <li>Con. If encapsulation is mandatory, we would have to pass the individual validators to the entity  (aggregate) method</li>
  </ul></li>
  <li><p>Validation encapsulated inside the entity</p>
  
  <ul>
  <li>Pro. Encapsulated?</li>
  <li>Pro. Reusable?</li>
  </ul></li>
  </ul>
  
  <p>I would love to read your thoughts about this</p>