问题
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).
回答1:
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.
回答2:
Yes, I think so
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.
You can refer more info in this page
来源:https://stackoverflow.com/questions/30190302/what-is-the-difference-between-invariants-and-validation-rules