AlgoViz

SOLID in one page

medium 45 min

Five principles for classes that can be changed without fear: single responsibility, open/closed, Liskov substitution, interface segregation and dependency inversion.

Watch lesson5:16

Contracts you can test

Turn Liskov from an opinion into a test suite that every kind must pass.

The point: O is a promise to your colleagues: add a kind without reading the core. That promise is worth as much as the test that stops a bad kind.

Contract

What belongs into it

PartQuestionSender
PreconditionWhat may the caller pass?Any text, also empty and very long. Any name
PostconditionWhat is true afterwards?ok means: the whole text was handed over
ErrorsWhat can go wrong, and how is it said?Receipt with a reason. Wrong types may still raise
StateDoes a call change what the caller sees?The arguments are unchanged
RepetitionWhat if it is called twice?Two messages, unless a wrapper says otherwise
TimeHow long may it take?At most 5 seconds (assumed here)
ThreadsFrom how many at once?From several
Most Liskov violations hide in the last four rows. The compiler sees none of them.

One contract test for all kinds

The test knows the promise, not the kinds. It returns every broken clause by name.

from dataclasses import dataclass@dataclass(frozen=True)class Receipt:    ok: bool    detail: str = ""TEXTS = ["", "x", "disk 95%", "y" * 160, "z" * 161, "long " * 100]def broken_clauses(make):    """make() returns (sender, delivered, sabotage). The names of all broken clauses."""    bad = set()    for text in TEXTS:        sender, delivered, _ = make()        try:            r = sender.send("ops", text)        except Exception as e:            bad.add("raises " + type(e).__name__)            continue        if not isinstance(r, Receipt):            bad.add("returns " + type(r).__name__)        elif r.ok and "".join(delivered()) != text:            bad.add("ok, but text lost")    sender, delivered, sabotage = make()    sabotage()    try:        r = sender.send("ops", "x")        if r.ok:            bad.add("ok although the line is down")        elif not r.detail:            bad.add("failure without a reason")    except Exception as e:        bad.add("raises " + type(e).__name__ + " when down")    return bad

Line 10

The texts are chosen at the borders: empty, one, exactly 160, 161. A bug in a limit lives there.

1 of 4

A new pager can only carry 20 characters. It cannot keep the whole text clause. What do you do?

BreaksMake it a Sender that cuts
How
It compiles, and the list accepts it.
Limit
The core's promise is now false for one kind. Somebody will write if sender.name == "pager".
Choose when
Never.
WorksWeaken the contract for all
How
send delivers at least the first 20 characters.
Limit
Every caller loses the guarantee that email kept.
Choose when
If no caller needs the whole text.
StrongAnother, smaller contract
How
Beeper.beep(to, code) with a code of 20 characters, and a service step that sends a code and a full text elsewhere.
Limit
The service learns a second idea. But that idea is real.
Choose when
When the difference matters to the caller.

Where to run it

PlaceWhat it catches
Unit tests with a rigLogic at the borders
Against the provider's sandbox, every nightThe provider changed
In the core, at the boundaryA kind that lies in production: check that a receipt came back, count and isolate