Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Invariants and Validation Rules?

Tags:

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).

like image 971
wonderful world Avatar asked May 12 '15 12:05

wonderful world


People also ask

What are invariants in DDD?

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.

What is an aggregate in DDD?

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.


1 Answers

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.

like image 98
guillaume31 Avatar answered Oct 05 '22 10:10

guillaume31