SOLID & Design Patterns Interview Question #86
What is an invariant in domain modeling?
DDD Boundaries, Resilience, Caching & Practical ASP.NET Core Design Mid-Level Intermediate
Quick Interview Answer
An invariant is a business rule that must remain true whenever an aggregate is in a valid state. The aggregate should prevent operations that would violate its invariants.
Detailed Explanation
An invariant is a business rule that must remain true whenever an aggregate is in a valid state. The aggregate should prevent operations that would violate its invariants.
Examples include preventing a confirmed order from being empty or ensuring a withdrawal does not exceed an account's permitted balance. Keeping invariants inside the domain boundary reduces invalid intermediate states.
Code Example
public void Confirm()
{
if (_items.Count == 0)
throw new DomainException(
"An empty order cannot be confirmed.");
Status = OrderStatus.Confirmed;
}