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).
In DDD, validation rules can be thought as invariants. The main responsibility of an aggregate is to enforce invariants across state changes for all the entities within that aggregate. Domain entities should always be valid entities. There are a certain number of invariants for an object that should always be true.
Aggregate is a pattern in Domain-Driven Design. A DDD aggregate is a cluster of domain objects that can be treated as a single unit. An example may be an order and its line-items, these will be separate objects, but it's useful to treat the order (together with its line items) as a single aggregate.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With