Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your instinct is right. In DDD objects should never be allowed to enter a state that is not valid from domain perspective. Even temporarily. Objects should protect their internal invariants, this is pretty basic OOP. Otherwise it would not be an object but just a dumb data container. Often times people get confused by the UI frameworks or they overgeneralize the term 'validation'.</p> <p>For example every Product in your system should have SKU. Or every Customer should have social security number. Enforcing these rules is the direct responsibility of Product and Customer entities. Good old ArgumentNullException will let client code realize that it broke some invariant. Enforcing this rule is not a responsibility of UI or some abstract 'Validator'. If you let this rule be enforced outside your entity you will:</p> <ul> <li><p>eventually end up with invalid state which can result in crash or will require you to write some compensation code to avoid this crash</p></li> <li><p>more importantly, you will not be able to reason about the Product by just reading Product code</p></li> </ul> <p>Furthermore business rules are usually more complex than that so it would be even harder to enforce them outside of the entity without breaking its encapsulation. There is another group of rules that can be easily enforced by using DDD <a href="http://domaindrivendesign.org/node/135" rel="nofollow">Value Object</a>. In the above example you would create class 'SKU' and 'SocialSecurityNumber'. These classes will be immutable and will enforce all the formatting rules. They can also have static methods like:</p> <pre><code>SocialSecurityNumber.TryParse(String untrustedString, out SocialSecurityNumber) </code></pre> <p>or </p> <pre><code>SocialSecurityNumber.IsStringValid(String untrustedString) </code></pre> <p>UI can use these methods to validate user input. There is no reason for UI to 'break' objects even temporarily. If you let this happen you will end up with <a href="http://martinfowler.com/bliki/AnemicDomainModel.html" rel="nofollow">Anemic Domain Model</a>. Unfortunately a lot of sample code on the internet promotes this approach. The bottom line is that your validation rules are coming from your domain and they should be enforced by domain objects.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload