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

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

ObjectionWhat is right about itAnswer
S is vague: what is one reason?Yes, as a sloganUse actors and commit history, not feeling
O invites guesses about the futureYes, if used earlyWait for the second or third kind
They lead to too many tiny classesOften seenThe other half of S: keep together what changes together
They are from the time of class treesL and O were first told with inheritanceAll five work with functions, modules and services
They say nothing about whether the program is rightTrueThey 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

Python
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)
The alert service in functions. All five letters are there, and not one class with a method.
Edit and run it in your browser

When each form fits

UseWhen
A functionOne operation, no state, few parameters
A closure, as aboveOne operation with a little fixed setup
A classState, several operations on it, or a name that readers look for
An interfaceTwo kinds, or something foreign
DataOnly values differ

Cost

Count before you believe

Python
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)
Interfaces with a single implementation, found by reading the source. Stand-ins in tests are not counted as a second one.
Edit and run it in your browser

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 IThing for each Thing.
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.