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

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)
The starting point. A dozen lines, five future problems.
Edit and run it in your browser

Five wishes, five pains

WishWhat hurtsLetter
Operations want the host name in the textThe text sits between sending and history. Both are tested againS
A chat channel, then a pagerAnother elif, and the old branches are at riskO
SMS texts arrive without their endOne branch breaks a promise that nobody wrote downL
Support wants to read repliesSMS can, email can, pager cannot: an empty method appearsI
A test without a mail serverSmtp() is created insideD

The bad shape

AlertManager- smtp: Smtp- file: List+ alert(sev, to, msg, kind)SmtpClient+ mail(to, text)

1/3Text and mail

The manager formats and creates its own mail client.

owns (dies together)uses

The rule (who is alerted with what) depends on three details.