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
Smell
One class, and five changes that hurt in five different ways.
The point: the five letters are five kinds of pain. Show the pain first, then name the letter.
Task
Alerts for a monitoring system
When a disk is full, somebody must be told. The first version formats the text, picks the channel, sends and keeps a history. All in one class.
Python
class Smtp: def mail(self, to, text): return "250 ok"class AlertManager: def __init__(self): self.smtp, self.file = Smtp(), [] def alert(self, severity, to, message, kind): text = "[" + severity.upper() + "] " + message if kind == "email": self.smtp.mail(to, text) elif kind == "sms": text = text[:160] # silently cut else: raise ValueError(kind) self.file.append((to, text))m = AlertManager()m.alert("critical", "ops@example.com", "Database disk 95% full", "email")print(m.file)Five wishes, five pains
| Wish | What hurts | Letter |
|---|---|---|
| Operations want the host name in the text | The text sits between sending and history. Both are tested again | S |
| A chat channel, then a pager | Another elif, and the old branches are at risk | O |
| SMS texts arrive without their end | One branch breaks a promise that nobody wrote down | L |
| Support wants to read replies | SMS can, email can, pager cannot: an empty method appears | I |
| A test without a mail server | Smtp() is created inside | D |
The bad shape
1/3Text and mail
The manager formats and creates its own mail client.
owns (dies together)uses