Comparison
Class invariantvsDesign by contract
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 →Design by contract
the method states what must be true when you call it and what will be true when it returns, and it checks both.
Specifying a method by a precondition the caller must satisfy, a postcondition the method guarantees, and an invariant the object maintains throughout. It makes the division of blame explicit — a precondition violation is the caller's bug, a postcondition violation is the callee's — which is why it clarifies Liskov substitution so well. Few languages support it directly, so it usually survives as argument checks at the top of a method and assertions in tests.
Full entry →