SOLID in one page
medium 45 minFive principles for classes that can be changed without fear: single responsibility, open/closed, Liskov substitution, interface segregation and dependency inversion.
Watch lesson5:16
Five steps
One small refactor per letter, each with the reason to stop.
The point: five commits. After each one the tests are green, and you could stop. That is the difference between a refactor and a rewrite.
S
Step 1: text, sending and history get owners
Python
class AlertFormatter: def format(self, severity, message, host="unknown"): return "[" + severity.upper() + "] " + host + ": " + messageassert AlertFormatter().format("critical", "disk 95%", "db1") == "[CRITICAL] db1: disk 95%"print("text tested without sending")O
Step 2: channels are a list
Python
class Email: def send(self, to, text): return "email to " + toclass Chat: def send(self, to, text): return "chat to " + todef notify(senders, to, text): return [s.send(to, text) for s in senders]print(notify([Email()], "ops", "x"))print(notify([Email(), Chat()], "ops", "x"))L
Step 3: write the promise down
| Part of the promise | Before | Now |
|---|---|---|
| Text | SMS cut it | The whole text arrives, in parts if needed |
| Result | None, or a string, or an error | Always a Receipt(ok, detail) |
| A refused number | Exception | Receipt(False, reason): refusal is an answer |
| Network down | Exception of the library | Receipt(False, reason) too: the caller need not know libraries |
| Called twice | Two messages | Two messages, and the contract says so |
I
Step 4: replies are another interface
Python
from typing import Protocol, runtime_checkableclass Sender(Protocol): def send(self, to, text): ...@runtime_checkableclass ReplyReader(Protocol): def replies(self): ...class Sms: def send(self, to, text): return True def replies(self): return ["on my way"]class Pager: def send(self, to, text): return True # and no replies() that raisesdef support_inbox(readers: list[ReplyReader]): return [line for r in readers for line in r.replies()]print(support_inbox([Sms()]), isinstance(Pager(), ReplyReader))D
Step 5: hand things in
The service names what it needs (Sender, History, a clock) in its own words. Mail server, gateway and file live in adapters. One function creates all and connects them.
Which way the arrows point
When you could stop
| After | Good enough if |
|---|---|
| S | One channel, and only texts change |
| O | All channels behave alike |
| L | Nobody needs more than sending |
| I | Tests with a real server are fast enough |
| D | Always. Now only wiring is left |