Search code examples
validationdomain-driven-designinvariants

What is the difference between Invariants and Validation Rules?


I often see the term Invariants in DDD. Here Dino Esposito talks about it. If I look at the .NET library, I see a ValidationAttribute class. Are Invariants and validation rules the same? For example, can I say 50% discount is available only if the order total is more than $250 is an Invariant?

Or are they different where Invariants are to protect an object from becoming invalid and validation is to check the validity of the object even after it has changed it's state (it can be in a valid or invalid state)? In the above example, if I use invariants, I check for the invariant before updating the discount and in the case of validation, I apply the 50% discount and then check for the validity (the object is already is in invalid state).


Solution

  • Absolutely, validation is the process of approving a given object state, while invariant enforcement happens before that state has even been reached.

    A corollary is that invariant enforcement is best performed by the thing that is being mutated (or created) itself, like a self-protection reflex, whereas validation is usually done by a third party.

    The Always valid school of thought advocates the use of invariants over validation. I think it goes perfectly with DDD and Aggregates.