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
Criticism
Good objections, and how to answer them without a fight.
The point: a strong candidate knows the weak sides. SOLID has real ones. Saying them first shows that you use the principles and do not believe in them.
Objections
Five that deserve an answer
| Objection | What is right about it | Answer |
|---|---|---|
| S is vague: what is one reason? | Yes, as a slogan | Use actors and commit history, not feeling |
| O invites guesses about the future | Yes, if used early | Wait for the second or third kind |
| They lead to too many tiny classes | Often seen | The other half of S: keep together what changes together |
| They are from the time of class trees | L and O were first told with inheritance | All five work with functions, modules and services |
| They say nothing about whether the program is right | True | They make change cheap. Tests, names and domain knowledge do the rest |
Dan North goes further and proposes CUPID: composable, Unix philosophy, predictable, idiomatic, domain-based. These are properties to move towards, not rules that a class obeys or breaks. It is a helpful second view. Predictable is close to L, Unix philosophy is close to S, and domain-based asks something that SOLID never asks: does the code speak the language of the business?
Without classes
The same five with functions
from collections import namedtupleAlert = namedtuple("Alert", "severity host message")def format_alert(a): # S: one owner return "[" + a.severity.upper() + "] " + a.host + ": " + a.messagedef make_notify(fmt, senders, remember): # D: everything handed in def notify(alert, to): text = fmt(alert) results = [send(to, text) for send in senders] # O and L: any function (to, text) -> bool remember((text, sum(results))) return sum(results) return notifydef to_chat(out): # I: a sender is one function def send(to, text): out.append((to, text)) return True return sendout, history = [], []notify = make_notify(format_alert, [to_chat(out), lambda to, text: False], history.append)print(notify(Alert("critical", "db1", "disk 95%"), "ops"), history)When each form fits
| Use | When |
|---|---|
| A function | One operation, no state, few parameters |
| A closure, as above | One operation with a little fixed setup |
| A class | State, several operations on it, or a name that readers look for |
| An interface | Two kinds, or something foreign |
| Data | Only values differ |
Cost
Count before you believe
import astSOURCE = """class Sender(Protocol): ...class Email(Sender): ...class Sms(Sender): ...class History(Protocol): ...class FileHistory(History): ...class FakeHistory(History): ...class Formatter(ABC): ...class PlainFormatter(Formatter): ..."""FOREIGN = {"History"} # a real border: keep it with one implementationkinds = {}for node in ast.parse(SOURCE).body: bases = [b.id for b in node.bases] if set(bases) & {"Protocol", "ABC"}: kinds[node.name] = [] for b in bases: if b in kinds and not node.name.startswith("Fake"): kinds[b].append(node.name)for name, impl in kinds.items(): verdict = "keep" if len(impl) > 1 else "keep, border" if name in FOREIGN else "look at it" print(name, impl, verdict)When not to use it
A script
One owner, one use, read top to bottom.
A prototype
You do not know the axes yet. Guessing them is worse than none.
Hot inner loops
Millions of small calls through an interface can matter. Measure, then flatten that loop only.
Generated or stable code
Nobody changes it by hand.
A new team lead asks for a rule: every class gets an interface. What do you say?
BreaksAgree, it is SOLID
- How
- A tool creates
IThingfor eachThing. - Limit
- Twice the files, no new freedom, and go to definition ends nowhere.
- Choose when
- Never.
WorksRefuse
- How
- YAGNI.
- Limit
- The real wish, testing without servers, stays unsolved.
- Choose when
- If nothing hurts.
StrongAsk what hurts, and write a smaller rule
- How
- Interfaces at borders (network, disk, time, other teams) and from the second kind on. Count once a quarter.
- Limit
- Needs judgement in reviews.
- Choose when
- Any team above a few people.