title: Validating domain model in Spring
body: <p>I would like to find way how to make sure that if domain model object is created it's valid in meaning that meets all business rules, for example:</p>
  
  <ul>
  <li>Customer has valid contact address</li>
  <li>Address consists of all required fields</li>
  <li>et cetera</li>
  </ul>
  
  <p>I have an idea to have for every domain object model own class that works as a validator class and is used for validation that the instance is valid.</p>
  
  <pre><code>public interface IValidator {    
      public boolean isValid();    
  }
  </code></pre>
  
  <p>Simplified illustration of interface implementation for AccountType domain model class:</p>
  
  <pre><code>public final class AccountTypeValidator implements IValidator {
  
      private final AccountType accountType;
  
      public AccountTypeValidator(final AccountType accountType) {
          this.accountType = accountType;
      }
  
      public boolean isValidName() {
          if (StringUtils.isBlank(accountType.getName()) == true) {
              return false;
          }
          return true;
      }
  
      public final boolean isValid() {
          if (isValidName() == false) {
              return false;
          }
          return true;
      }
  
  }
  </code></pre>
  
  <p>and when I use this validation class in my application I can do something like it:</p>
  
  <pre><code>    public void setAccountType(final AccountType accountType) {
  
          AccountTypeValidator validator = new AccountTypeValidator(accountType);
  
          if (validator.isValid() == false) {
              throw new IllegalArgumentException("....");
          }
  
          this.accountType = accountType;
  
      }
  </code></pre>
  
  <p><strong>Pros:</strong></p>
  
  <ul>
  <li>Define own validation rules for all my domain models</li>
  <li>Validate all object or concrete fields I am interested in</li>
  <li>Get error validation messages indicating what fields are not valid (and use it in as description in exception e.g.)</li>
  </ul>
  
  <p><strong>Cons:</strong></p>
  
  <ul>
  <li>Define own validation rules to all domain models</li>
  <li>When I have many objects (instances of AccountType class for example) I need to create new object for all of them (resources consumption)</li>
  </ul>
  
  <p>I am sure that there is no need to reinvent the wheel, so I would like to ask you if is there something (library, best practice etc.) what can be used to solve this situation. I googled, I red principles of "Design by contract" concept and found some corresponding themes here on SO but still I am not sure what is the best way how to solve it. </p>
  
  <p>I would like to find solution that is maximally simple, solution that consumes minimum system resources, is easy to use and is robust in meaning that makes sure that domain model objects are valid.</p>