Comparison
Always-valid domain modelvsClass invariant
Always-valid domain model
you could not construct an invalid one, so nothing downstream had to check whether it was valid.
The stance that an object should enforce its invariants at construction and at every mutation, so an instance in a bad state cannot exist. It removes defensive checking everywhere downstream and makes an invalid state a construction-time error rather than a runtime discovery. The usual objection is form validation, where you need to collect several errors at once rather than fail on the first — which is an argument for validating input separately, not for letting the model be invalid.
Full entry →Class invariant
there is a rule that is true of the object at every moment a caller can see it, and the constructor is where it starts being true.
A condition an object guarantees between every public operation: a date range whose end is never before its start, an order whose total always equals the sum of its lines. The value is that once it holds, no method needs to re-check it, which removes a large amount of defensive branching. It is also the argument for constructors that validate and for immutability, because both remove the windows in which it could be false.
Full entry →