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
Tensions
Letters against letters, with a decision for each.
The point: senior questions are not about one letter. They are about two that disagree. Decide by the next change, and say what the other letter loses.
Case 1
S says split, O says: the engine must see all
Two alerts of one host should be joined into one message. Each sender could do it (then each must know the others), or the service could. Joining is about how alerts meet, so it belongs to the core. The service grows by one step and stays one actor.
Case 2
I says small, callers want many
from typing import Protocolclass Sender(Protocol): def send(self, to, text): ...class ReplyReader(Protocol): def replies(self): ...class Conversation(Sender, ReplyReader, Protocol): ... # for the one caller who needs bothclass Sms: def __init__(self): self.lines = [] def send(self, to, text): self.lines.append("to " + to + ": " + text) def replies(self): return ["on my way"]def ask(c: Conversation, to, question): c.send(to, question) return c.replies()[-1]print(ask(Sms(), "lee", "who takes it?"))Case 3
D says port, YAGNI says not yet
| Dependency | Port on day one? | Why |
|---|---|---|
| Mail provider | Yes | Foreign, slow, costs money, fails in its own way |
| Clock | Yes, as a function | Tests need to set the time |
| Database | A repository class. An interface when a second one exists | The test may use a real small database |
| Standard library list, JSON | No | Stable, fast, not yours to replace |
| Another class of the same owner | No | Call it directly |
| Another team's service | Yes | Other release rhythm |
Case 4
L against the real world
A read-only list looks like a list. But callers of a list may call add. Java's Collection answers with optional operations: the documentation allows UnsupportedOperationException. That is a contract which says: ask first. It keeps the number of interfaces small and moves the check from the compiler to run time. Python's collections.abc chose the other way: Sequence can read, MutableSequence can also write.
Read first, write on top
1/4The smaller promise on top
Reading is what both can do.
extends (is a)implements
Case 5
O against a closed set
| Grows | Shape | Who helps you |
|---|---|---|
| Kinds (new senders) | Interface and classes | The contract test |
| Operations (export, print, count) | Closed set of kinds and functions with an exhaustive match | The compiler lists the missing cases |
| Neither | Plain if | Nobody needed |
| Both | Open functions or visitors with care | Expect work |
Two letters disagree