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.

Chapter mnemonic

Five SOLID design questions

One job. Bolt on extras. Swap a part. Pack small kits. Fit a standard socket.

A replacement part fits, but it breaks behavior the caller relies on. Which SOLID principle is at stake?

Liskov substitution. A subtype must honor the behavioral contract of its supertype.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 5:16

SOLID in one page

1:07Reel

SOLID in one page in one picture
SOLID in one page in one picture

Theory

Read or listen first. About 3 min.

What it is

SOLID is a set of five design principles. Each answers one question about change. S: who may ask for a change here? O: can a new kind arrive without an edit? L: can I trust every kind to keep the promise? I: does each caller see only what it needs? D: does the important code depend on details?

They are not five separate rules. S cuts the program into pieces, I cuts the contracts between the pieces, D decides which way the arrows point, O is what you gain from that, and L is the condition under which it stays true.

They are advice, not laws. Each has a price: more names, more files, more jumps while reading. You pay where change is likely and leave the rest simple.

Why it exists

In a low-level design round the interviewer changes the requirements in the last ten minutes. A design of long if chains and god classes falls apart at that moment. A design along these five questions answers with a new class and one line of wiring.

In daily work the gain is the same: small changes stay small, tests need few stand-ins, and two teams can work side by side.

The five words are also a shared language. A review that says this subtype breaks the contract is shorter and kinder than one that says I do not like it.

A short history

  1. 1987

    Barbara Liskov gives the keynote Data Abstraction and Hierarchy, with the idea of substitution. In 1994 Liskov and Jeannette Wing make it precise.

  2. 1988

    Bertrand Meyer names the open/closed principle in Object-Oriented Software Construction.

  3. 1996

    Robert C. Martin publishes The Open-Closed Principle (January) and The Dependency Inversion Principle (June) in the C++ Report.

  4. 1990s

    Martin formulates interface segregation while consulting for Xerox, where one large Job class served stapling, faxing and printing. In the late 1990s Martin names single responsibility.

  5. 2000

    Martin collects principles in the paper Design Principles and Design Patterns, as an answer to software that rots.

  6. About 2004

    Michael Feathers notices that five of them spell SOLID.

  7. 2022

    Dan North publishes CUPID, five properties that are meant as an answer to SOLID. The debate is useful: see the page on criticism.

Words to know

Actor
A group of people who may ask for a change. The unit of single responsibility.
Contract
What a caller may rely on: the method, what it accepts, what it returns, what it never does.
Subtype
A class that can stand wherever its parent or interface is expected.
Precondition
What must be true before a call. A subtype may ask for less, never for more.
Postcondition
What is true after a call. A subtype may promise more, never less.
Invariant
What is always true for an object between two calls.
Port
A small interface owned by the important code, for something outside, such as mail or storage.
Adapter
A class that fits a foreign thing to a port.
Dependency injection
Handing an object its collaborators from outside. One way to reach dependency inversion.
Composition root
The one place where objects are created and connected.
Axis of change
One kind of change that a design makes cheap.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

How it works

Step through the idea, or press Play.

Step 1 of 4

Split by actor. S: one group of people per class

Understand it

Start here

Five ideas on one marble run

Asha builds a marble run on a board. The marble should roll through all pieces and ring a bell. Each of the five letters is a way in which such a run works or fails.

Asha's marble run

Frames 1 and 2 are the problem, 3 to 7 the five letters, 8 the limit.

The map

One question per letter

LetterAskSmellUsual moveFull page
S ingle responsibilityWho may ask for a change here?God class, many stand-ins in testsSplit by actor, thin coordinatorSRP
O pen/closedDoes a new kind need an edit?if kind == that keeps growingA contract and a list of kindsOCP
L iskov substitutionCan I use any kind without looking?isinstance, NotImplementedErrorWrite the contract down, test every kindLSP
I nterface segregationDoes this caller need all of that?Empty methods, fat interfacesOne small interface per callerISP
D ependency inversionDoes the rule know the detail?new SmtpClient() inside a ruleThe rule owns a port, the detail implements itDIP
The pages go deep. Here each letter gets one example, and then the five work together.

What hurts? Follow it to a letter

The last branch is part of the map.

S

Single responsibility: one group of people

A class should have one reason to change. This does not mean one method. It means that all its methods serve one actor.

Python
# before: three reasons to change in one methodclass UserService:    def register_user(self, email, password, db, smtp):        if "@" not in email: raise ValueError("invalid email")       # rules        db.append(("INSERT", email))                                 # storage        smtp.append(("welcome", email))                              # mail# afterclass UserValidator:    def validate(self, email, password):        if "@" not in email: raise ValueError("invalid email")        if len(password) < 8: raise ValueError("password too short")class UserRepository:    def __init__(self): self.rows = []    def save(self, email):                # the password hash would go here, never the password        self.rows.append(email)        return emailclass Notifier:    def __init__(self): self.sent = []    def send_welcome(self, user): self.sent.append(user)class UserRegistrationService:    def __init__(self, validator, repo, notifier):        self._validator, self._repo, self._notifier = validator, repo, notifier    def register_user(self, email, password):        self._validator.validate(email, password)        user = self._repo.save(email)        self._notifier.send_welcome(user)        return userrepo, notifier = UserRepository(), Notifier()print(UserRegistrationService(UserValidator(), repo, notifier).register_user("asha@example.com", "longenough"))print(repo.rows, notifier.sent)
After the split the service has one job: the order of the steps.
Edit and run it in your browser

O

Open/closed: new kinds as new code

Open for extension, closed for modification. A new payment method should be a new class. The checkout, which already works, is not opened.

Python
from abc import ABC, abstractmethodclass PaymentMethod(ABC):    @abstractmethod    def process_payment(self, cents: int) -> bool: ...class CreditCardPayment(PaymentMethod):    def process_payment(self, cents): return Trueclass CryptoPayment(PaymentMethod):    def process_payment(self, cents): return Trueclass CheckoutService:    def checkout(self, method: PaymentMethod, cents: int) -> bool:        if cents <= 0: raise ValueError("nothing to pay")        return method.process_payment(cents)class GiftCard(PaymentMethod):                  # new kind, nothing above was edited    def __init__(self, left): self.left = left    def process_payment(self, cents):        if cents > self.left: return False        self.left -= cents        return Trueshop, card = CheckoutService(), GiftCard(1000)print(shop.checkout(card, 700), shop.checkout(card, 700))    # True False
CheckoutService does not know the kinds. Money is whole cents.
Edit and run it in your browser

L

Liskov substitution: every kind keeps the promise

If S is a subtype of T, code that works with a T must go on working with an S, without knowing it. A subtype inherits the contract, not only the method names.

Four rules of a good subtype

  1. 1

    No unexpected errors

    A subtype does not throw what callers of the parent do not expect, such as UnsupportedOperationException.

  2. 2

    Never ask for more

    A precondition may become weaker, never stronger. If the parent accepts any text, the child may not refuse long ones.

  3. 3

    Never give less

    A postcondition may become stronger, never weaker. If the parent returns a receipt, the child may not return nothing.

  4. 4

    Keep the invariants

    A Square that changes its height when somebody sets the width breaks the promise of a mutable Rectangle: the sides are independent.

Python
class Email:    def send(self, to, text):        """Deliver the whole text. Return the number of characters delivered."""        return len(text)class Sms:                                  # keeps the promise: many parts, one answer    def send(self, to, text):        parts = [text[i:i + 160] for i in range(0, len(text), 160)]        return sum(len(p) for p in parts)class CutSms:                               # same signature, weaker promise    def send(self, to, text):        return len(text[:160])def alert(channel, text):    assert channel.send("ops", text) == len(text), type(channel).__name__ + " lost part of the text"    return "ok"long = "disk full " * 30print(alert(Email(), long), alert(Sms(), long))try:    alert(CutSms(), long)except AssertionError as e:    print(e)
The same caller, three kinds. One of them fits the signature and breaks the promise.
Edit and run it in your browser

I

Interface segregation: only what you use

Nobody should depend on methods that they do not use. Split a fat MultiFunctionDevice into Printable and Scannable. A class may implement both. A caller asks for one.

D

Dependency inversion: the rule owns the port

High-level code (the rules) should not depend on low-level code (database, mail). Both depend on an abstraction, and the abstraction is written in the language of the rules. Injection is only the handing over. A class can be injected with a concrete database client and still violate DIP.

Python
from typing import Protocolclass OrderReader(Protocol):                 # I: this service only reads orders    def get_order(self, order_id: str) -> dict: ...class AuditLogger(Protocol):                 # I: and only records lines    def record(self, message: str) -> None: ...class OrderFulfillmentService:               # D: it knows two ports, no database and no file    def __init__(self, reader: OrderReader, logger: AuditLogger):        self._reader, self._logger = reader, logger    def fulfill(self, order_id: str) -> str:        order = self._reader.get_order(order_id)        if not order["paid"]:            raise ValueError("not paid: " + order_id)        self._logger.record("Fulfilled order " + order_id)        return order["address"]class Orders:    def get_order(self, order_id): return {"paid": order_id != "o2", "address": "Lake Road 4"}class Lines(list):    def record(self, message): self.append(message)lines = Lines()print(OrderFulfillmentService(Orders(), lines).fulfill("o1"), lines)
I and D together: two small protocols, owned by the service, and a test without any server.
Edit and run it in your browser

Together

How the five need each other

Who helps whom

Read I to L: a small promise is easier to keep. Read L to O: one kind that breaks its promise forces a special case into the core, and the core is open again.

Take one letter away

WithoutWhat you getSeen as
SPerfect interfaces around a god classThe interface has 30 methods, and nobody can implement it twice
OClean pieces, but the core lists all kindsif channel == "sms" next to a beautiful Channel interface
LKinds that fit and lieThe core asks isinstance again
IStubs: methods that raise NotImplementedErrorLSP broken by force: a class must promise what it cannot do
DContracts owned by the database packageEach change of the driver changes the rules

Where they pull apart

TensionExampleDecide by
S against easy readingNine classes for one use caseMerge what always changes together
O against YAGNIAn extension point for one kindWait for the second or third kind
I against one ideaSeven interfaces with one method eachSplit per caller, not per method
D against directnessA port for the standard library's listPorts only for what is foreign, slow or likely to change
L against realityA read-only list is almost a listDo not subtype. Make a smaller interface both can keep
If two letters disagree, look at the next three changes that you really expect. They decide.

Pragmatic SOLID

  • Start with simple objects, and extract an interface when a second kind appears
  • Keep foreign SDKs behind small ports, with Strategy and injection
  • Prefer composition to deep trees, so that promises are easy to keep
  • Write small tests with few stand-ins that prove the borders

Over-engineering

  • An interface for each helper class before anybody asked
  • Six levels of inheritance that copy the real world
  • NotImplementedError inside overridden methods
  • Connection pools and HTTP clients inside domain objects

Patterns that carry the letters

  • Strategy

    O and D: one algorithm behind a contract. See Strategy.

  • Adapter

    D: a foreign class made to fit our port. See Adapter.

  • Decorator

    O and S: extras around a call, each in its own class. See Decorator.

  • Observer

    O: new listeners without an edit. See Observer.

  • Factory

    D: the only place with concrete names. See Factory.

  • Composition

    L: no inherited promise to break. See inheritance or composition.

A 400 line class works, has one owner, and has not changed for two years. Somebody calls it not SOLID. What do you do?

BreaksRefactor it to be safe
How
Ports, kinds, a factory.
Limit
New bugs in code that had none, for a change nobody asked for.
Choose when
Never without a wish.
WorksLeave it
How
Stable code with one owner fulfils the goal.
Limit
The next wish may find it hard to test.
Choose when
Nothing is planned.
StrongLeave it, write the missing tests, decide at the next wish
How
Pin the behaviour now. When a wish comes, use the one letter that it needs.
Limit
Discipline: the wish must not be squeezed in.
Choose when
Old code that earns money.

Summary

The whole topic in one minute.

S: one group of people per class. O: new kinds arrive as new code. L: every kind keeps the promise. I: callers see only what they use. D: important code owns the contract, details follow it.

Apply them from the change backwards: take the wish that comes next, see how many files it touches, and use the one letter that shortens the list.

Stop in time. One implementation, a closed set of kinds or a small script need none of this.

  • Single responsibility: each class answers to one group of people.
  • Open/closed: new behaviour as new classes behind a contract, on an axis you chose.
  • Liskov substitution: subtypes never ask for more, give less, or surprise.
  • Interface segregation: small contracts, so that nobody writes stubs.
  • Dependency inversion: rules own the ports, details implement them.
  • Together: S and I cut, D turns the arrows, O is the gain, L keeps it true.

Sources