Skip to content

Patterns

The hard part of a property isn’t the code. It’s knowing what rule to check, when you can’t write down the right answer for every input. These patterns are rules that turn up again and again. Each page has a short example with a real bug in it, the failure proptastic prints, when to reach for the pattern, and what it won’t catch.

Pattern The rule Reach for it when Example
Round trip Undoing gives back what you started with. One function undoes another: encode and decode, format and parse. Money that formats one cent as 0.1.
Idempotence Doing it twice is doing it once. Code cleans or normalizes, or may run again by accident. A name tidier that leaves two spaces of three.
Invariant A rule holds after every operation. An object changes over time, and a rule must always hold. A playlist capped at five that takes a sixth.
Commutativity The order of two inputs doesn’t matter. Two things of a kind are combined: sums, merges, unions. Combining baskets where one count replaces the other.
Conservation Nothing is made or lost. Something is moved or split, and its total should stay put. A bill split that loses the leftover cents.
Compare with a reference A simple way and the clever way agree. A slow, obviously right way to get the answer exists. A binary search that never looks at the last place.
Metamorphic Changing the input changes the answer as it should. You can’t say what the answer is, but you know how answers relate. A heavier parcel that costs less.

A property can use more than one. The bank account checks conservation, that transfers keep the total, then an invariant, that no balance goes below zero after any step.

The patterns say what to check. Domains says what to check it on. Further reading lists the papers behind each pattern.

Privacy