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.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
One alert program goes through all five letters. Watch which object must change, and which need not know.
Operations
Five wishes, one class
The starting point. Every wish ends in the same object.
Step 1 of 5
S: another text
Operations want the host in the text. The line sits between sending and storing.
Step 1: S: another text
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] self.file.append((to, text))- Good for
- Two fixed channels
- Costs
- Every wish is an edit
Name the pain before you name the letter.
In the real world
The same solid in one page doing real jobs. Pick one and step through it.
Pluggable discounts and an injected tax policy: the practice problem, acted out.
Step 1 of 5
One book, twice
Two books at 20 make 40. No rules yet.
Step 1: One book, twice
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Injection taken for inversion
majorThe client is handed in, and the rule still speaks SQL.
Wrongdef __init__(self, mysql): ...def run(self): self.mysql.execute("SELECT ...")Rightdef __init__(self, orders: OrderReader): ...def run(self): self.orders.unpaid()A method that only raises
criticalThe class promises what it cannot do, and a caller will believe it.
Wrongdef replies(self): raise NotImplementedErrorRightclass Pager: # a Sender, nothing else def send(self, to, text): ...Asking for the kind
criticalOne isinstance, and the core must be edited for the next exception.
Wrongif isinstance(s, Pager): text = text[:20]Rightbeeper.beep(to, code) # a smaller contractStricter than the parent
majorCallers only know the parent's demands.
Wrongdef send(self, to, text): if not text: raise ValueErrorRightdef send(self, to, text): parts = split(text) # empty text: no partsInterface per class
minorTwice the files, no new freedom.
Wrongclass IAlertFormatter(Protocol): ...class AlertFormatter(IAlertFormatter): ...Rightclass AlertFormatter: ...All five at once
majorA rewrite without a wish has only risk.
Wronggit commit -m "make it SOLID"Rightgit commit -m "chat channel: extract Sender"
Interview tips
Wish first
- Ask what comes next
- Use the one letter it needs
- Say where you stop
Promise in words
- Errors, limits, repetition
- One test for all kinds
- Good day and bad day
Look at arrows
- Details point at rules
- Who owns the interface?
- One place creates things
Count
- Files per change
- Stand-ins per test
- Interfaces with one class