Skip to content

Lesson 1 of 28Principles

SOLID Principles

Spot the five classic design smells in Python and TypeScript, fix them, and know when the fix is overkill.

28 min read0/6 questions

Problem Solving taught you to get from a vague task to working code. This course asks the next question: will that code still be easy to change in a year? Code that works today still has to survive next month's feature request. SOLID is five rules of thumb, collected by Robert C. Martin around 2000, that make classes cheaper to change. Interviewers ask about them constantly, and code reviewers use them (often without naming them) every day.

Each principle below follows the same shape: a real smell (a sign that something will hurt later), then the fix, in both Python and TypeScript.

S: single responsibility

A class should have one reason to change. "Reason to change" means one group of people or one kind of requirement. If the finance team changes the tax rule and the design team changes the PDF layout, and both edits land in the same class, that class has two jobs.

smell
class InvoiceService:
    def total(self, items): ...        # finance rules
    def render_html(self, items): ...  # design rules
    def email(self, html, to): ...     # infrastructure
Python
class InvoiceCalculator: TAX = 0.2 def total(self, items: list[tuple[str, int]]) -> int: subtotal = sum(price for _, price in items) return round(subtotal * (1 + self.TAX)) class InvoiceRenderer: def render(self, items: list[tuple[str, int]], total: int) -> str: lines = [f"{name}: {price}" for name, price in items] return "\n".join(lines + [f"TOTAL: {total}"]) items = [("Hosting", 1000), ("Domain", 200)]total = InvoiceCalculator().total(items)print(InvoiceRenderer().render(items, total))
Output
Press Run (⌘ Enter) to see what happens.

Now a tax change touches one small class with one small test file. A layout change cannot break the maths.

O: open for extension, closed for modification

You should be able to add behaviour without editing code that already works. The classic smell is a growing if/elif chain on a type name. Every new export format means reopening the same function, and every reopen risks breaking CSV while you add XML.

smell
def export(rows, fmt):
    if fmt == "csv": ...
    elif fmt == "json": ...
    elif fmt == "xml": ...   # edited again for every new format
Python
import json EXPORTERS = {} def exporter(fmt: str): def register(fn): EXPORTERS[fmt] = fn return fn return register @exporter("csv")def to_csv(rows: list[dict]) -> str: header = ",".join(rows[0]) return "\n".join([header] + [",".join(str(v) for v in r.values()) for r in rows]) @exporter("json")def to_json(rows: list[dict]) -> str: return json.dumps(rows) # Adding TSV later is a new function. Nothing above changes.@exporter("tsv")def to_tsv(rows: list[dict]) -> str: return "\n".join("\t".join(str(v) for v in r.values()) for r in rows) rows = [{"id": 1, "plan": "pro"}, {"id": 2, "plan": "free"}]print(EXPORTERS["csv"](rows))print(EXPORTERS["tsv"](rows))
Output
Press Run (⌘ Enter) to see what happens.
Quick check
Which change best signals an Open/Closed violation?
Need a nudge? A hint rules out a wrong answer.

L: Liskov substitution

Named after Barbara Liskov (1987). If code works with a parent type, it must keep working when you hand it any subtype. A subclass may do more, but it must not break the parent's promises: same inputs accepted, same kind of outputs, no surprise exceptions.

smell
class Cache:
    def get(self, key):  # promise: returns None on a miss
        ...
 
class RedisCache(Cache):
    def get(self, key):
        raise KeyError(key)  # breaks every caller that checks `is None`
Python
class Cache: def __init__(self): self._data: dict[str, str] = {} def get(self, key: str) -> str | None: return self._data.get(key) def set(self, key: str, value: str) -> None: self._data[key] = value class PrefixedCache(Cache): """Adds a namespace, but keeps the parent's promise: None on a miss.""" def __init__(self, prefix: str): super().__init__() self.prefix = prefix def get(self, key: str) -> str | None: return super().get(self.prefix + key) def set(self, key: str, value: str) -> None: super().set(self.prefix + key, value) def load_user(cache: Cache, user_id: str) -> str: cached = cache.get(user_id) if cached is not None: return f"{cached} (cache hit)" cache.set(user_id, f"user-{user_id}") return f"user-{user_id} (from db)" for cache in (Cache(), PrefixedCache("app:")): print(load_user(cache, "7"), "|", load_user(cache, "7"))
Output
Press Run (⌘ Enter) to see what happens.

A quick Liskov test: if a subclass method starts with raise NotImplementedError or throw new Error("not supported"), it probably should not be a subclass.

Liskov violations you will meet in real code

The cache example is tidy. Real violations are sneakier, because the subclass looks perfectly reasonable on its own. Three shapes come up again and again.

The read-only subtype. Someone needs an immutable list, so they subclass the list and make the mutating methods raise. Every function that accepts a list and appends to it now crashes when handed one. Python's own standard library avoids this: tuple is not a subclass of list, and collections.abc separates Sequence (read) from MutableSequence (read and write). The fix is the same in your code: make the read-only type the parent (or a separate interface), and the mutable one the child that adds methods. Adding abilities is safe. Removing them is not.

Square and Rectangle. At school a square is a rectangle, so Square(Rectangle) feels right. But a mutable Rectangle promises that setting the width leaves the height alone, and a square cannot keep that promise.

Predict the outputPython

What does this print?

class Rectangle:
  def __init__(self, w, h):
      self.w, self.h = w, h
  def set_width(self, w):
      self.w = w
  def set_height(self, h):
      self.h = h
  def area(self):
      return self.w * self.h

class Square(Rectangle):
  def __init__(self, side):
      super().__init__(side, side)
  def set_width(self, w):
      self.w = self.h = w
  def set_height(self, h):
      self.w = self.h = h

def stretch(r):
  r.set_width(5)
  r.set_height(4)
  return r.area()

print(stretch(Rectangle(1, 1)), stretch(Square(1)))
Need a nudge? Hints walk you through it.

Strengthened preconditions. A subtype may accept more than its parent, never less. A subclass that only accepts card payments, when the parent accepts any payment, will crash the first time generic code hands it something else. Weakened postconditions are the mirror image: the parent promises a non-empty result and the child sometimes returns None.

Type checkers catch part of this. In Python, mypy and pyright flag an override whose parameter type is narrower than the parent's (mypy even prints a note saying it violates the Liskov substitution principle). TypeScript is looser than most people expect: method parameters are checked bivariantly, even with strict on, so this compiles without a single error:

TypeScript
class Payment { constructor(public cents: number) {}}class CardPayment extends Payment { constructor(cents: number, public last4: string) { super(cents); }} class Refunder { refund(p: Payment): string { return `refunded ${p.cents}`; }} class CardRefunder extends Refunder { // Narrows the parameter type: a strengthened precondition. // TypeScript allows it, because method parameters are checked bivariantly. refund(p: CardPayment): string { return `refunded ${p.cents} to card ending ${p.last4.slice(-4)}`; }} const refunders: Refunder[] = [new Refunder(), new CardRefunder()];for (const r of refunders) { try { console.log(r.refund(new Payment(500))); } catch (e) { console.log("crash:", (e as Error).message); }}
Output
Press Run (⌘ Enter) to see what happens.

The strictFunctionTypes flag only applies to properties declared with function-type syntax, like refund: (p: Payment) => string. Declare a method that way when you want the compiler to reject a narrowed override. No type checker catches behavioural violations, like the square or a subclass that throws where the parent did not. Those you catch with a shared test suite that runs the parent's tests against every subclass.

I: interface segregation

Callers should not depend on methods they do not use. A fat interface forces every implementation to fake the parts it cannot do. Here is a notifier hierarchy before and after splitting it:

Fat interface vs small ones
Notifiersend_email, send_sms, send_pushEmailNotifiersms and push raise errorsSlackNotifieremail and sms raise errorsSendersend(to, text)EmailSenderSmsSenderSlackSenderroot

One big Notifier interface. Every class must implement three methods, so each one fakes two of them with errors. That also breaks Liskov.

1/3
Python
from typing import Protocol class Sender(Protocol): def send(self, to: str, text: str) -> str: ... class EmailSender: def send(self, to: str, text: str) -> str: return f"email to {to}: {text}" class SlackSender: def send(self, to: str, text: str) -> str: return f"slack #{to}: {text}" def alert_on_call(senders: list[Sender], text: str) -> None: for s in senders: print(s.send("oncall", text)) alert_on_call([EmailSender(), SlackSender()], "disk 91% full")
Output
Press Run (⌘ Enter) to see what happens.

Python's typing.Protocol is structural: any class with a matching send method counts as a Sender, no inheritance needed. TypeScript interfaces work the same way.

D: dependency inversion

High-level policy (checkout rules) should not depend on low-level detail (the Stripe SDK). Both should depend on an abstraction, and the detail gets passed in from outside. Passing it in is called dependency injection.

smell
class CheckoutService:
    def __init__(self):
        self.stripe = StripeClient(api_key="sk_live_...")  # hard-wired
Python
from typing import Protocol class PaymentGateway(Protocol): def charge(self, cents: int, token: str) -> str: ... class CheckoutService: def __init__(self, gateway: PaymentGateway): self.gateway = gateway def pay(self, cents: int, token: str) -> str: if cents <= 0: raise ValueError("amount must be positive") return self.gateway.charge(cents, token) class FakeGateway: def __init__(self): self.charges: list[int] = [] def charge(self, cents: int, token: str) -> str: self.charges.append(cents) return f"ch_{len(self.charges)}" fake = FakeGateway()service = CheckoutService(fake)print(service.pay(4999, "tok_visa"))print(fake.charges)
Output
Press Run (⌘ Enter) to see what happens.

Production code passes a real StripeGateway. Tests pass FakeGateway and run in milliseconds with no network. That testability is the main payoff you will feel day to day.

Predict the outputPython

What does this print?

class Fake:
  def __init__(self):
      self.calls = 0
  def charge(self, cents, token):
      self.calls += 1
      return "ok"

class Checkout:
  def __init__(self, gateway):
      self.gateway = gateway
  def pay(self, cents):
      if cents <= 0:
          return "rejected"
      return self.gateway.charge(cents, "tok")

f = Fake()
c = Checkout(f)
c.pay(0)
c.pay(500)
print(f.calls)
Need a nudge? Hints walk you through it.

DIP vs dependency injection vs inversion of control

These three terms get blurred, and interviewers like to ask you to separate them. They sit at three different levels.

  • Inversion of control (IoC) is the broadest idea: something else calls your code, instead of your code calling it. A framework that calls your route handler, a test runner that calls your test functions, and a callback you pass to sort are all IoC. "Don't call us, we'll call you."
  • Dependency injection (DI) is one specific form of IoC, about creation: an object receives its dependencies instead of constructing them. Constructor parameters are DI. FastAPI's Depends and NestJS's injector are DI done by a framework.
  • The dependency inversion principle (DIP) is about the direction of source-code dependencies: high-level policy and low-level detail both depend on an abstraction, and the abstraction belongs to the high-level side. It is a design rule, not a technique.

You can do one without the others. Injecting a concrete StripeClient into CheckoutService is DI without DIP: the service still depends on Stripe's class. Defining a PaymentGateway protocol in the checkout module, but letting CheckoutService construct StripeGateway() itself, honours DIP on paper while hard-wiring the detail. In practice you want both: the abstraction owned by the business code (DIP), and the concrete class passed in at the composition root (DI).

Quick check
CheckoutService(stripe_client: StripeClient) receives the real Stripe SDK client through its constructor. Which statement is accurate?
Need a nudge? A hint rules out a wrong answer.
Match the pairs0/5 matched

Match each smell to the principle it breaks.

Choose an item, then its match on the other side.

SOLID without classes

SOLID was written in the language of classes, but every principle is about dependencies and reasons to change, and those exist in a codebase of plain functions and modules too. Most modern TypeScript, and a lot of Python, is written that way. The translation:

PrincipleIn a class-heavy codebaseIn a functional or module-based codebase
Single responsibilityOne class, one reason to changeOne module, one reason to change (pricing.ts has no I/O)
Open/closedSubclasses or strategy objectsA registry of functions, or a union type plus an exhaustive switch
LiskovSubclasses keep the parent's promisesEvery function that fits a type keeps the same contract
Interface segregationSmall interfacesNarrow parameter types: Pick<User, "email">, not User
Dependency inversionInject an interfaceInject a function, or a small object of functions
TypeScript
// S: one module, one reason to change. Here, pricing rules only.type Discount = | { kind: "percent"; pct: number } | { kind: "fixed"; cents: number } | { kind: "bogo" }; type Line = { sku: string; cents: number; qty: number }; function applyDiscount(d: Discount, line: Line): number { const gross = line.cents * line.qty; switch (d.kind) { case "percent": return Math.round(gross * (1 - d.pct / 100)); case "fixed": return Math.max(0, gross - d.cents); case "bogo": return line.cents * Math.ceil(line.qty / 2); default: { const unreachable: never = d; // compile error if a new kind is not handled return unreachable; } }} // I: ask for the narrowest shape you need, not the whole User.type User = { id: string; email: string; name: string; passwordHash: string };function receiptHeader(user: Pick<User, "name" | "email">): string { return `${user.name} <${user.email}>`;} // D: depend on a function type, and inject it.type SendEmail = (to: string, body: string) => Promise<void>; function makeCheckout(deps: { sendEmail: SendEmail }) { return async (user: Pick<User, "name" | "email">, line: Line, d: Discount) => { const total = applyDiscount(d, line); await deps.sendEmail(user.email, `${receiptHeader(user)} paid ${total}`); return total; };} // The test double is just a function that records calls.const sent: string[] = [];const checkout = makeCheckout({ sendEmail: async (to, body) => { sent.push(`${to}: ${body}`); } }); checkout({ name: "Ada", email: "ada@shop.dev" }, { sku: "MUG", cents: 1200, qty: 3 }, { kind: "bogo" }) .then((total) => { console.log(total); console.log(sent); });
Output
Press Run (⌘ Enter) to see what happens.

Two details here deserve a second look. The never check in the switch turns a missing case into a compile error: add { kind: "freeShipping" } to the union and TypeScript points at every switch that does not handle it. That is a deliberate trade against Open/Closed. A union is closed to new variants (you edit the type) but makes adding new operations cheap and safe. A registry or class hierarchy is the reverse: new variants are cheap, new operations touch every class. This trade-off has a name, the expression problem, and choosing the right side for your domain matters more than following either rule blindly. Discount kinds change rarely and get new operations often (display, validate, apply), so a union fits.

Second, makeCheckout takes { sendEmail } instead of an EmailService class. A function type is the smallest possible interface, so Interface Segregation and Dependency Inversion come almost for free, and a test double is one line.

A worked refactor through all five

Principles click when you watch them fix one real piece of code. Here is a class in the shape you will meet in a codebase that grew fast: one method parses, validates, prices, picks shipping, writes to the database, sends email and formats a receipt. A subclass handles preorders.

orders.py (before)
import datetime
import json
import smtplib
import sqlite3
 
 
class OrderProcessor:
    def __init__(self):
        self.db = sqlite3.connect("shop.db")
        self.smtp = smtplib.SMTP("smtp.shop.dev")
 
    def process(self, order_json: str, shipping: str, receipt_format: str) -> str:
        # 1. parse and validate
        order = json.loads(order_json)
        if not order.get("items"):
            raise ValueError("empty order")
        if "@" not in order.get("email", ""):
            raise ValueError("bad email")
 
        # 2. price
        subtotal = 0
        for item in order["items"]:
            subtotal += item["price"] * item["qty"]
        if order.get("coupon") == "SAVE10":
            subtotal = subtotal * 0.9
 
        # 3. shipping
        if shipping == "standard":
            shipping_cost = 500
        elif shipping == "express":
            shipping_cost = 1500
        elif shipping == "pickup":
            shipping_cost = 0
        else:
            raise ValueError("unknown shipping")
        total = round(subtotal) + shipping_cost
 
        # 4. save
        cur = self.db.cursor()
        cur.execute(
            "INSERT INTO orders (email, total, created) VALUES (?, ?, ?)",
            (order["email"], total, datetime.datetime.now().isoformat()),
        )
        self.db.commit()
        order_id = cur.lastrowid
 
        # 5. email
        body = f"Thanks! Order {order_id}, total {total / 100:.2f}"
        self.smtp.sendmail("shop@shop.dev", order["email"], body)
 
        # 6. receipt
        if receipt_format == "text":
            return f"Order {order_id}: {total / 100:.2f}"
        elif receipt_format == "json":
            return json.dumps({"id": order_id, "total": total})
        else:
            raise ValueError("unknown format")
 
 
class PreorderProcessor(OrderProcessor):
    def process(self, order_json, shipping, receipt_format):
        if shipping == "pickup":
            raise NotImplementedError("preorders cannot be picked up")
        return super().process(order_json, shipping, receipt_format)

Count the reasons to change: a coupon rule, a new shipping option, a schema change, a new email provider, a new receipt format. Five teams could need to edit this one method in the same week. And it cannot be tested without a real database file and an SMTP server.

Work through it one principle at a time, and keep the tests green after each step (the clean code lesson covers that loop).

  1. S. Pull pricing into a pure function price_items. It now has unit tests with no setup at all.
  2. O. Replace the shipping and receipt elif chains with dicts. A new option is a new entry.
  3. L. PreorderProcessor throws for an input the parent accepts, a strengthened precondition. Delete the subclass. Preorders become configuration: the set of allowed shipping options.
  4. I. The use case needs to save one order and send one email. Define two one-method protocols instead of depending on a full repository and a full mail client.
  5. D. Pass the saver and mailer into the constructor. The SQLite and SMTP adapters are built in the composition root and are the only code that imports sqlite3 or smtplib.
After the refactor
orders/pricing.pyS: price_items, COUPONS, pureoptions.pyO: SHIPPING, RECEIPTS registriesports.pyI: OrderSaver, Mailer (one method each)place_order.pyD + L: PlaceOrder use casesqlite_saver.pyimplements OrderSaversmtp_mailer.pyimplements Maileradapters/main.pycomposition root wires adapters inroot

Business rules with no I/O. A coupon change touches one small file and its fast tests.

1/5

Here is the result, in one file so you can run it, with its tests:

Python
import jsonfrom dataclasses import dataclassfrom typing import Callable, Protocol # S: pricing is pure business rules, with no I/O at all.@dataclass(frozen=True)class Item: price: int # cents qty: int COUPONS: dict[str, float] = {"SAVE10": 0.9} def price_items(items: list[Item], coupon: str | None) -> int: if not items: raise ValueError("empty order") subtotal = sum(i.price * i.qty for i in items) return round(subtotal * COUPONS.get(coupon or "", 1.0)) # O: a new shipping option or receipt format is a new entry, not a new elif.SHIPPING: dict[str, int] = {"standard": 500, "express": 1500, "pickup": 0} RECEIPTS: dict[str, Callable[[int, int], str]] = { "text": lambda oid, total: f"Order {oid}: {total / 100:.2f}", "json": lambda oid, total: json.dumps({"id": oid, "total": total}),} # I: each port has only the one method this use case needs.class OrderSaver(Protocol): def save(self, email: str, total: int) -> int: ... class Mailer(Protocol): def send(self, to: str, body: str) -> None: ... # D: the use case gets its dependencies passed in.# L: preorders are configuration (allowed shipping), not a subclass that throws.class PlaceOrder: def __init__(self, saver: OrderSaver, mailer: Mailer, allowed_shipping: set[str] | None = None): self.saver, self.mailer = saver, mailer self.allowed = allowed_shipping or set(SHIPPING) def __call__(self, email: str, items: list[Item], coupon: str | None, shipping: str, receipt: str) -> str: if shipping not in self.allowed: raise ValueError(f"shipping {shipping!r} not available; choose from {sorted(self.allowed)}") total = price_items(items, coupon) + SHIPPING[shipping] order_id = self.saver.save(email, total) self.mailer.send(email, f"Thanks! Order {order_id}, total {total / 100:.2f}") return RECEIPTS[receipt](order_id, total) # ---- Tests: fakes, no database, no SMTP, run in microseconds.class FakeSaver: def __init__(self): self.rows: list[tuple[str, int]] = [] def save(self, email, total): self.rows.append((email, total)) return len(self.rows) class FakeMailer: def __init__(self): self.sent: list[str] = [] def send(self, to, body): self.sent.append(to) def test_pricing_applies_coupon(): assert price_items([Item(1000, 2)], "SAVE10") == 1800 def test_place_order_saves_mails_and_formats(): saver, mailer = FakeSaver(), FakeMailer() place = PlaceOrder(saver, mailer) out = place("ada@shop.dev", [Item(1000, 2)], "SAVE10", "express", "json") assert saver.rows == [("ada@shop.dev", 3300)] assert mailer.sent == ["ada@shop.dev"] assert json.loads(out) == {"id": 1, "total": 3300} def test_preorders_reject_pickup_before_saving(): saver = FakeSaver() place = PlaceOrder(saver, FakeMailer(), allowed_shipping={"standard", "express"}) try: place("ada@shop.dev", [Item(500, 1)], None, "pickup", "text") except ValueError as e: assert "not available" in str(e) else: raise AssertionError("expected pickup to be rejected") assert saver.rows == [] for test in [test_pricing_applies_coupon, test_place_order_saves_mails_and_formats, test_preorders_reject_pickup_before_saving]: test() print("PASS", test.__name__)
Output
Press Run (⌘ Enter) to see what happens.

Notice what the tests no longer need: no database file, no mail server, no patching. Also notice what did not happen. There is no abstract base class for pricing, no factory for PlaceOrder, no interface for the coupon table. Each change was driven by a concrete pain in the original, which is the YAGNI rule below applied in practice.

When SOLID hurts: YAGNI

YAGNI means "you aren't gonna need it". Every interface, registry and injected dependency is indirection: one more file to open, one more name to learn. If there is exactly one exporter and no second one on the roadmap, a plain function is better than an Exporter interface with a single implementation.

SituationDo this
One payment provider, tests need to fake itInject it (DIP pays off for tests alone)
One export format, no second in sightPlain function, no registry
Third elif on the same type switchNow extract a registry or polymorphism
Subclass would raise "not supported"Use composition or a smaller interface

A good default: write the simple version, and refactor toward a principle the moment the code actually resists a change. The principles describe where pain comes from. They are not a checklist to apply up front.

Quick check
A teammate adds AbstractNotifierFactory, NotifierProvider and INotifier for an app that only ever sends email. What is the best review comment?
Need a nudge? A hint rules out a wrong answer.

How this course is laid out

The course has six units. Principles covers SOLID, clean code and the classic design patterns. Keeping code healthy is about refactoring, technical debt, coupling, pure functions and concurrency. Architecture scales up to layers, hexagonal design, React structure, monoliths, microservices and events. Domain-driven design shows how to model a business in code. Quality and safety covers testing strategy, contracts, threat modeling and the anti-patterns to avoid. Decisions and evolution closes with APIs that last and architectures that change safely.

By the end you will be able to structure a service, defend its design in a review, and change it without a rewrite. The course closes with a wrap-up that uses every unit on one piece of work.

Your turn

ChallengeEasy

Inject the sender

Build a SignupService that depends on an injected sender instead of creating one. The sender is any object with a send(to, text) method.

register(email) should:

  • normalise the email (strip spaces, lowercase it)
  • return False and send nothing if the email has no @
  • return False and send nothing if that email is already registered
  • otherwise remember the email, call sender.send(email, "Welcome!") exactly once, and return True
service = SignupService(fake_sender)
service.register("  Ada@Example.com ")  ->  True   (sends "Welcome!" to ada@example.com)
service.register("ada@example.com")     ->  False  (already registered)
service.register("nope")                ->  False

The tests pass in a fake sender that records what it was asked to send. That is the whole point of dependency inversion.

class SignupService: def __init__(self, sender): # Keep the injected sender. Do not create a real one here. pass def register(self, email: str) -> bool: pass
Key terms
single responsibility
A class has one reason to change: one kind of requirement owned by one group.
open/closed
Add new behaviour by adding code (a new class or registry entry), not by editing working code.
Liskov substitution
Any subtype must work wherever its parent type is expected, keeping the parent's promises.
interface segregation
Prefer several small interfaces over one fat one, so no class fakes methods it cannot support.
dependency inversion
Business logic depends on an abstraction; the concrete detail is injected from outside.
YAGNI
You aren't gonna need it. Do not build abstractions for variations that do not exist yet.
inversion of control
A framework or caller controls the flow and calls into your code, rather than your code calling it.
precondition
What a method requires of its inputs. A subtype may loosen it but must never tighten it.
method bivariance
TypeScript's rule that method parameters may be narrowed in overrides, which lets some Liskov violations compile.
expression problem
The trade-off between making new variants cheap (classes, registries) and making new operations cheap (union types).