Design by contract: guard the invariants
Let the object keep its own rules, so no caller can break them.
Watch the narrated video
Every step
Problem
Steps 1–3Refactor
Steps 4–9Payoff
Steps 10–12Recap
Steps 13–14The code: before and after
Before
class Stock:
def __init__(self, on_hand: int) -> None:
self._on_hand = on_hand
self._reserved = 0
@property
def on_hand(self) -> int:
return self._on_hand
@on_hand.setter
def on_hand(self, value: int) -> None:
self._on_hand = value
@property
def reserved(self) -> int:
return self._reserved
@reserved.setter
def reserved(self, value: int) -> None:
self._reserved = value
class OrderDesk:
def reserve(self, stock: Stock, quantity: int) -> None:
if quantity < 1 or quantity > stock.on_hand - stock.reserved:
raise ValueError(f"cannot reserve {quantity}")
stock.reserved += quantity
class Dispatch:
def ship(self, stock: Stock, quantity: int) -> None:
if quantity < 1 or quantity > stock.reserved:
raise ValueError(f"cannot ship {quantity}")
stock.reserved -= quantity
stock.on_hand -= quantity
lamps = Stock(10)
OrderDesk().reserve(lamps, 8)After
class Stock:
def __init__(self, on_hand: int) -> None:
self._on_hand = on_hand
self._reserved = 0
self._check_invariant()
@property
def on_hand(self) -> int:
return self._on_hand
@property
def reserved(self) -> int:
return self._reserved
@property
def available(self) -> int:
return self._on_hand - self._reserved
def reserve(self, quantity: int) -> None:
if quantity < 1 or quantity > self.available:
raise ValueError(f"cannot reserve {quantity}")
self._reserved += quantity
self._check_invariant()
def ship(self, quantity: int) -> None:
if quantity < 1 or quantity > self._reserved:
raise ValueError(f"cannot ship {quantity}")
self._reserved -= quantity
self._on_hand -= quantity
self._check_invariant()
def write_off(self, quantity: int) -> None:
if quantity < 1 or quantity > self.available:
raise ValueError(f"cannot write off {quantity}")
self._on_hand -= quantity
self._check_invariant()
def _check_invariant(self) -> None:
if not 0 <= self._reserved <= self._on_hand:
raise RuntimeError("invariant broken")
class OrderDesk:
def reserve(self, stock: Stock, quantity: int) -> None:
stock.reserve(quantity)
class Dispatch:
def ship(self, stock: Stock, quantity: int) -> None:
stock.ship(quantity)
class Damage:
def write_off(self, stock: Stock, quantity: int) -> None:
stock.write_off(quantity)
lamps = Stock(10)
OrderDesk().reserve(lamps, 8)
Damage().write_off(lamps, 5)
Dispatch().ship(lamps, 8)Transcript, step by step
Problem
Step 1: Ten desk lamps in stock Before
This is a small shop's stock of one product, desk lamps, and it keeps two counts, on hand and reserved. Each count is a property with a setter, and the order desk and dispatch both check the counts first and then set them. The shop starts with ten lamps and reserves eight of them for customers.
Step 2: Write off damaged lamps Change request
The warehouse wants to write off damaged lamps, so we add a Damage class with a write off method. It lowers on hand through the setter and checks nothing, because nothing tells its author there's a rule to keep. At the bottom, the shop now writes off five lamps and then ships the eight it reserved.
Step 3: Every caller keeps the rule Code smell
The stock has a rule, reserved is never more than on hand, and here every caller has to remember it, because the stock itself never checks. The order desk checks it here, dispatch checks only reserved here and trusts that on hand still covers it, and the new write off checks nothing here. Start with ten on hand and eight reserved, then write off five, and you have five lamps for eight promised orders. Dispatch then ships eight from five on hand, so on hand drops to minus three, and no error shows up anywhere. Every new caller of a setter is one more place where someone can forget the rule.
Refactor
Step 4: Back it out, refactor first Plan
Let's back the write off out. The rule belongs to the stock, so we'll move every check into Stock first, and then add the write off there.
Step 5: Name what's available Extract Method
First, on hand minus reserved gets a name, available, as a read-only property on Stock. The order desk's guard reads it, so the check means the same and still raises for the same quantities.
Step 6: Stock reserves itself Move Function
Next, reserve moves into Stock, with the guard clause as its first lines. That guard is the method's precondition, what must be true before the call, and any caller can read it right at the top. The order desk now just calls stock dot reserve, and the same quantities still raise the same Value Error.
Step 7: Stock ships itself Move Function
Ship moves the same way, and its precondition says you can only ship lamps that are reserved. Dispatch is down to one line that calls stock dot ship.
Step 8: Delete the setters Remove Setting Method
Nothing outside Stock assigns on hand or reserved anymore, so we delete both setters. From here on, only Stock's own methods change its counts, and the leading underscore tells readers to leave those fields alone, though Python won't stop anyone who ignores it.
Step 9: Check the invariant Introduce Assertion
An invariant is a rule about an object's fields that holds after every public method, and here it's that reserved is never below zero and never above on hand. Check Invariant raises a Runtime Error when that rule breaks, and the constructor, reserve and ship each call it as their last line. A check at the end of a method is a postcondition, so the invariant is now a promise of every method that changes the stock. We raise on purpose, because running Python with the dash O flag strips out every assert statement. The one new behavior is in the constructor, which now refuses a negative on hand, because a stock of minus one breaks the invariant.
Payoff
Step 10: Add the write off again Payoff
Now the write off goes back in, this time as a method on Stock. Its precondition says you can only write off lamps that nobody reserved, and after lowering on hand it checks the invariant. Damage calls stock dot write off in one line, just like the order desk and dispatch. Reserve, ship and check invariant didn't change at all.
Step 11: It fails at the write off Payoff
Run the same day again, with ten on hand and eight reserved, and write off five. Only two lamps are available, so the write off raises right at the call with cannot write off five, and the counts stay ten and eight. The lamps are still broken, so the warehouse has to cancel three reservations first, but someone sees the overselling today, at the write off, before dispatch ships anything.
Step 12: Why it was easy Payoff
The order desk and dispatch now hold no checks, and the write off states its own precondition at the top. If a later method forgets its precondition, check invariant still raises before that method returns, so the error shows up at that call and not later at dispatch. The precondition is what keeps the counts unchanged, and the invariant catches what a missing precondition lets through. That's design by contract, and it fits here because the rule belongs to the stock, so the stock states and checks it once, and callers only meet a precondition they can read on the method.
Recap
Step 13: Where we started, where we ended Before / after
On the left, Stock had a setter for each count and checked nothing itself. The order desk and dispatch each kept the rule with their own guard, and dispatch kept only half of it. On the right, Stock reserves and writes off through methods that check their preconditions first. Check invariant guards the rule at the end of each one, and the order desk is down to a single call.
Step 14: When to reach for it Takeaways
Reach for 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. You'll spot it by callers that check an object's fields before they set them, with the same check in several places. Python's own date class works this way, because it checks the day against the month when you build one and raises a Value Error for February thirtieth.