I'll Be Backend
Principles

Design by Contract: Guard the Invariants

Design by contract means a method states what it needs and what it promises, and the class states what is always true about its fields. When an object only has setters, every caller has to remember its rules, and the first caller that forgets breaks them silently. These lessons take a shop's stock of desk lamps, move the checks from its callers into the stock as preconditions, delete the setters and guard the invariant, so a new write off can't oversell.

Pick your language

When to use it

Use it when

An object has a rule between its fields, and several callers change those fields.

Skip it when

The object is plain data with no rule between its fields, like a record the code only reads.

Spot it by

Callers that check an object's fields before calling its setters, with the same check in several places.