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

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")
The text is a class with one owner. The host name is now an edit of this class only.
Edit and run it in your browser

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"))
The branch became a loop over objects. Chat is a class and a line of wiring.
Edit and run it in your browser

L

Step 3: write the promise down

Part of the promiseBeforeNow
TextSMS cut itThe whole text arrives, in parts if needed
ResultNone, or a string, or an errorAlways a Receipt(ok, detail)
A refused numberExceptionReceipt(False, reason): refusal is an answer
Network downException of the libraryReceipt(False, reason) too: the caller need not know libraries
Called twiceTwo messagesTwo messages, and the contract says so
The last row is allowed. A contract need not promise everything. It must say what it does not promise.

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))
The pager promises only what it can do. Support asks for something that can read replies.
Edit and run it in your browser

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

Calls still go from the service to the mail server. Only the dependencies in the source code turned around.

When you could stop

AfterGood enough if
SOne channel, and only texts change
OAll channels behave alike
LNobody needs more than sending
ITests with a real server are fast enough
DAlways. Now only wiring is left