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.
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.
class InvoiceService:
def total(self, items): ... # finance rules
def render_html(self, items): ... # design rules
def email(self, html, to): ... # infrastructurePress Run (⌘ Enter) to see what happens.class InvoiceService {
total(items: Item[]) { /* finance rules */ }
renderHtml(items: Item[]) { /* design rules */ }
email(html: string, to: string) { /* infrastructure */ }
}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.
def export(rows, fmt):
if fmt == "csv": ...
elif fmt == "json": ...
elif fmt == "xml": ... # edited again for every new formatPress Run (⌘ Enter) to see what happens.function exportRows(rows: Row[], fmt: string) {
if (fmt === "csv") { /* ... */ }
else if (fmt === "json") { /* ... */ }
else if (fmt === "xml") { /* edited again for every new format */ }
}Press Run (⌘ Enter) to see what happens.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.
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`Press Run (⌘ Enter) to see what happens.class Cache {
get(key: string): string | undefined { /* undefined on a miss */ }
}
class StrictCache extends Cache {
get(key: string): string { throw new Error("miss"); } // breaks callers
}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.
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)))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:
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:
One big Notifier interface. Every class must implement three methods, so each one fakes two of them with errors. That also breaks Liskov.
Press Run (⌘ Enter) to see what happens.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.
class CheckoutService:
def __init__(self):
self.stripe = StripeClient(api_key="sk_live_...") # hard-wiredPress Run (⌘ Enter) to see what happens.class CheckoutService {
private stripe = new StripeClient("sk_live_..."); // hard-wired
}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.
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)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
sortare 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
Dependsand 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).
CheckoutService(stripe_client: StripeClient) receives the real Stripe SDK client through its constructor. Which statement is accurate?Match each smell to the principle it breaks.
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:
| Principle | In a class-heavy codebase | In a functional or module-based codebase |
|---|---|---|
| Single responsibility | One class, one reason to change | One module, one reason to change (pricing.ts has no I/O) |
| Open/closed | Subclasses or strategy objects | A registry of functions, or a union type plus an exhaustive switch |
| Liskov | Subclasses keep the parent's promises | Every function that fits a type keeps the same contract |
| Interface segregation | Small interfaces | Narrow parameter types: Pick<User, "email">, not User |
| Dependency inversion | Inject an interface | Inject a function, or a small object of functions |
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.
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).
- S. Pull pricing into a pure function
price_items. It now has unit tests with no setup at all. - O. Replace the shipping and receipt
elifchains with dicts. A new option is a new entry. - L.
PreorderProcessorthrows for an input the parent accepts, a strengthened precondition. Delete the subclass. Preorders become configuration: the set of allowed shipping options. - 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.
- 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
sqlite3orsmtplib.
Business rules with no I/O. A coupon change touches one small file and its fast tests.
Here is the result, in one file so you can run it, with its tests:
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.
| Situation | Do this |
|---|---|
| One payment provider, tests need to fake it | Inject it (DIP pays off for tests alone) |
| One export format, no second in sight | Plain function, no registry |
Third elif on the same type switch | Now 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.
AbstractNotifierFactory, NotifierProvider and INotifier for an app that only ever sends email. What is the best review comment?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
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
Falseand send nothing if the email has no@ - return
Falseand send nothing if that email is already registered - otherwise remember the email, call
sender.send(email, "Welcome!")exactly once, and returnTrue
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") -> FalseThe tests pass in a fake sender that records what it was asked to send. That is the whole point of dependency inversion.
- 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).