2026.11.18 · 13 min · typescript · javascript · architecture · career
An introduction to the SOLID principles.
The five SOLID principles on small TypeScript examples: a signup broken by an email tweak, a checkout that grows payment methods, a subclass that compiles and crashes, a widget type that turns every file red, and an OrderService that builds its own Stripe client. What each principle actually says, where it came from, and the readings people get wrong.
SOLID gets taught as five slogans, and each slogan has a popular wrong reading. So I made a five-part Instagram series, one letter per day, each on one small TypeScript example that breaks and then gets fixed. This post collects all five, with the sources behind each one. Michael Feathers coined the acronym around 2004; the principles themselves are older.
1. S: the Single Responsibility Principle
A whole feature goes into one UserService because it "belongs to users". It checks the form, saves the user and sends the welcome email:
class UserService {
async signup(form: SignupForm) {
if (!form.email.includes("@")) throw new Error("Bad email");
const user = await db.users.insert(form);
await mailer.send(user.email, `Welcome, ${user.name}!`);
return user;
}
}Marketing asks for a first-name greeting: `Hi ${user.profile.firstName}`. profile is undefined, so a TypeError is thrown after the insert. Signup returns a 500, and the retry fails with "email taken". The user was saved and never told.
Robert C. Martin's original wording was "each software module should have one and only one reason to change". In 2014 he said what a reason is: "the reasons for change are people. It is people who request changes." Clean Architecture (2018) gives the final form: "A module should be responsible to one, and only one, actor." His own example is an Employee class with calculatePay (the CFO's people), reportHours (the COO's) and save (the CTO's): three actors, three reasons to change.
Here product owns the form rules, the backend team owns saving and marketing owns the email. One module each:
// validateSignup.ts · userRepo.ts · welcomeEmail.ts
async function signup(form: SignupForm) {
validateSignup(form);
const user = await userRepo.save(form);
sendWelcomeEmail(user).catch(logError);
return user;
}Two things are doing the work here, and I want to be honest about both. The split decides where marketing's edit lands: one file, one reviewer. The .catch without an await is what keeps a broken email from failing signup. Split the files but keep awaiting the email without a catch, and the same bug still takes signup down.
What people get wrong:
- "One responsibility means it does one thing." Clean Architecture calls SRP possibly "the least well understood" SOLID principle for exactly this reason. "A function should do one, and only one, thing" is a real rule, but the book says it "is not one of the SOLID principles".
- Counting methods. A 10-method module follows SRP if one actor owns all of it. A one-liner breaks it if two actors edit it.
- Over-splitting. Taken too far, the wrong reading gives "ravioli code": 20 tiny files. One actor's code can stay in one module.
- "Module" means class. It means a source file or a cohesive group of functions, which fits JS and TS well.
The ideas are older than the name: Parnas (1972) split modules by the decisions likely to change, alongside Dijkstra's separation of concerns and Constantine's cohesion. Martin put them together in the late 1990s. The practical test: ask who would ask you to change this line?
2. O: the Open/Closed Principle
Every checkout grows payment methods: card, UPI, PayPal, then Apple Pay. If each one is another else if inside checkout(), every addition reopens the most money-critical function in the app, and every old method needs testing again. Miss a branch and the order falls through to a runtime error.
Bertrand Meyer coined the principle in Object-Oriented Software Construction (1988): modules should be "both open and closed". His version used inheritance. Martin restated it in C++ Report in January 1996 around abstract interfaces and polymorphism, and that's the reading SOLID teaches. His plain version: "You should be able to extend the behavior of a system without having to modify that system."
// Before: every new method edits checkout()
function checkout(order: Order) {
if (order.method === "card") return chargeCard(order);
else if (order.method === "upi") return chargeUpi(order);
else if (order.method === "paypal") return chargePaypal(order);
throw new Error("Unknown method"); // forgot one? fails at runtime
}
// After
interface PaymentMethod { pay(order: Order): Promise<Receipt>; }
// applePay.ts: the new method is a new file
export const applePay: PaymentMethod = { pay: (o) => /* ... */ };
const methods: Record<string, PaymentMethod> = { card, upi, paypal, applePay };
function checkout(order: Order) {
return methods[order.method].pay(order); // never changes
}The honest count is a new file plus one line: applePay still has to go into the methods map, unless you auto-register. And methods[order.method] can be undefined, so guard it or type the key as a union. Martin's clearest picture is a plugin architecture: "The plugins know about the system", not the other way round.
What people get wrong:
- "Closed" means never touching the code again. You still fix bugs and register the new method. The point is that adding a variant shouldn't mean rewriting tested logic. Jon Skeet thinks the word itself misleads: this "is simply not how the word 'closed' is used elsewhere".
- Closing against everything. Martin's 1996 paper says "no significant program can be 100% closed". You choose which kinds of change to close against, and he admits most features still get added by changing existing code.
- Building the interface on day one. Wait for the second or third variant. A two-branch
ifthat never changes is fine. - Thinking
switchis the sin. In TypeScript, a discriminated union with an exhaustiveswitchand anevercheck catches the missed branch at compile time. The problem is editing it for every new method.
3. L: the Liskov Substitution Principle
extends feels like free reuse. You have an AppStorage that can load and save, and a saveDraft() that takes any storage. Then you need a read-only one, so you extend AppStorage and make save() throw. TypeScript compiles it:
// Before: compiles fine
class AppStorage {
load(key: string): string | null { /* … */ return null; }
save(key: string, value: string): void { /* … */ }
}
class ReadOnlyStorage extends AppStorage {
save(): void { throw new Error("Storage is read-only"); }
}
function saveDraft(storage: AppStorage, draft: string) {
storage.save("draft", draft); // fine for every storage so far
}
saveDraft(new ReadOnlyStorage(), text); // runtime crashThe crash lands in saveDraft, a function that worked for months and that nobody touched. The bug lives in the hierarchy. Overriding with fewer parameters (save()) is legal TypeScript, which is why nothing warns you.
Barbara Liskov stated the idea in her OOPSLA 1987 keynote, "Data Abstraction and Hierarchy". With Jeannette Wing she made it precise in 1994: anything provable about a T must hold for an S that subtypes T. In practice a subtype can't require more (stronger preconditions), can't promise less (weaker postconditions) and can't throw new kinds of exceptions. Martin's 1996 paraphrase is the version SOLID teaches: "Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it." The shortest form I've seen: if X inherits from Y, X should pass all of Y's black box tests.
The fix lives in the hierarchy: the child only promises what it keeps.
// After: only promise what you keep
interface ReadableStorage { load(key: string): string | null; }
interface WritableStorage extends ReadableStorage {
save(key: string, value: string): void;
}
class ReadOnlyStorage implements ReadableStorage { load(key: string) { /* … */ return null; } }
function saveDraft(storage: WritableStorage, draft: string) { storage.save("draft", draft); }
saveDraft(new ReadOnlyStorage(), text);
// TS error: Property 'save' is missing in type 'ReadOnlyStorage'…Now the mistake shows up in the editor, not in production. TypeScript's own lib does the same: ReadonlyArray has no push, and a string[] is assignable to readonly string[] but not the other way round. Martin also ties L to O: a function that has to check which subtype it got must change for every new subtype.
What people get wrong:
- "Is-a" in English means "can extend". A read-only storage is a kind of storage in plain English, but it can't keep
save()'s promise. LSP is about behaviour, not names or signatures. - "The type checker would catch it." It checks shapes. An override that throws still type-checks.
- Every throw is a violation. Not if the parent's contract already says "may throw". Java marks the mutators of
Collections.unmodifiableListas "optional" operations, and people still argue over it as the textbook trade-off. The claim is narrower: a parent that promisessave()works.
4. I: the Interface Segregation Principle
A dashboard has one Widget type. The clock has no data to export, but the type demands exportCsv(), so the clock carries stubs just to compile. Then a ticket asks for print() on the sales chart. Someone adds one line to the shared type, and every widget file stops compiling.
The figure is illustrative: four widget files, one added member. TypeScript fails any object typed with an interface when a required member is missing ("Property … is missing … but required"), so one required addition to a shared type breaks every object that uses it, including the three that will never print.
Martin's wording (C++ Report, 1996): "Clients should not be forced to depend upon interfaces that they do not use." His reason is that such clients "are subject to changes to those interfaces", which couples code that has nothing else in common. He calls these "fat" or "polluted" interfaces, and the stubs "nil implementations". His own example is a security Door forced to carry a timer method: "Why should a bug in TimerClient have any affect on clients of Door derivatives that do not require timing?" The story goes that he first hit the problem consulting for Xerox on a printer system, where one Job class served almost every task; that account is second-hand and disputed in its details.
// Before: one type for every widget
interface Widget {
render(): HTMLElement;
refresh(): Promise<void>;
exportCsv(): string;
}
const clock: Widget = {
render: drawClock,
refresh: async () => {}, // stub
exportCsv: () => "", // stub
};
// Ticket: "Add print() for the sales chart"
// → clock.ts, weather.ts, notes.ts… all error
// After: small types, pick what you use
interface Widget { render(): HTMLElement }
interface Exportable { exportCsv(): string }
interface Printable { print(): void }
const clock: Widget = { render: drawClock };
const sales: Widget & Exportable & Printable = {…};
function exportButton(w: Exportable) { … }Sales picks three types; the clock picks one. TypeScript checks by shape, so exportButton happily accepts the big sales object and nothing has to declare implements. Pick<T, K> cuts a small type out of a big one when you can't change the original. Rob Pike's Go proverb says the same thing from another language: "The bigger the interface, the weaker the abstraction."
What people get wrong:
- One method per interface. Group members by who uses them, not as small as possible. Over-splitting has its own cost.
- "It's only for classes with
implements." It applies just as much to props and function parameters. A component that takes the wholeuser: Userbut reads onlynamedepends on every field it never uses. - Making the extras optional (
exportCsv?). That hides the problem: every caller now has to check forundefined. - Stubs that throw. These stubs return empty values. A stub that throws is the Liskov crash from part 3, and Martin notes nil stubs drift that way.
5. D: the Dependency Inversion Principle
OrderService creates its own Stripe client. Every test of checkout() now calls Stripe (or needs module mocking), and "we're moving providers" means editing the class that holds your order rules.
// Before
import Stripe from "stripe";
class OrderService {
private stripe = new Stripe(process.env.STRIPE_KEY!);
async checkout(order: Order) {
await this.stripe.paymentIntents.create({ amount: order.totalCents, currency: "usd" });
}
}Martin's 1996 C++ Report column, verbatim: "A. High level modules should not depend upon low level modules. Both should depend upon abstractions. B. Abstractions should not depend upon details. Details should depend upon abstractions." When the important code depends on the detail, he writes, changes to the lower level "can force them to change", and he calls that "absurd". His own example is a Copy() that calls WritePrinter() and so can't write to a disk without an if per device.
The fix: OrderService declares the interface it needs, and that interface lives in its file.
// After: order-service.ts owns the interface
export interface PaymentGateway { charge(cents: number): Promise<void>; }
export class OrderService {
constructor(private payments: PaymentGateway) {}
checkout(order: Order) { return this.payments.charge(order.totalCents); }
}
// stripe-gateway.ts: the detail depends on the abstraction
export class StripeGateway implements PaymentGateway { /* new Stripe(...) lives here */ }
new OrderService(new StripeGateway()); // production
new OrderService({ charge: async () => {} }); // test, no networkBefore, the arrow ran from OrderService down to Stripe. Now StripeGateway imports PaymentGateway from the high-level file, so the arrow from the low level points up. That flip is the name: traditional structured design has high-level modules depend on low-level ones, and a good OO design's dependency structure is "inverted" relative to that. The abstractions are owned by the policy layer, so PaymentGateway lives next to OrderService, not in a Stripe folder.
| Term | What it is | Here |
|---|---|---|
| Dependency injection | handing an object its collaborators from outside (Fowler named it in January 2004) | the constructor(private payments …) parameter |
| Dependency inversion | who owns the interface, and which way the arrow points | PaymentGateway lives in order-service.ts |
What people get wrong:
- Inversion = injection, or = using an IoC container. Injection is the how. You can inject without inverting:
constructor(gateway: StripeGateway)is injected but still names the concrete class. - Shaping the interface after the vendor.
createPaymentIntent(params: Stripe.…)makes the abstraction depend on the detail, which breaks rule B. - "An interface with one implementation is pointless." The fake in your tests is the second one.
- Needing a framework. No DI container is required. Plain
newat the entry point is enough.
On a client project, the first thing I'd look for in a review is the new of a vendor SDK inside a class that holds business rules; moving it behind an interface that class owns is usually the cheapest change with the biggest payoff in tests.
The short version
- S: group code by who asks for changes to it (one actor per module), not by "does one thing".
- O: a new variant should be a new file plus one registration line, not another
else ifin tested code; wait for the second or third variant before abstracting. - L: a subtype keeps its parent's promises; if a child can't keep one, fix the hierarchy so it never makes it. TypeScript won't catch a throwing override.
- I: don't make code depend on members it never uses; split types by who uses them, not down to one method each.
- D: the high-level code owns the interface and the detail implements it; injection is how it gets in, inversion is which way the arrow points.
Sources: Martin, The Single Responsibility Principle (2014) · Wikipedia, Single-responsibility principle · Martin, Clean Architecture ch. 7 · Wikipedia, SOLID · Hacker News thread on SRP · sicpers.info, I've vastly misunderstood the SRP · LogRocket, SRP · Wikipedia, Open–closed principle · Martin, The Open Closed Principle (2014) · Martin, The Open-Closed Principle (C++ Report 1996) · Jon Skeet, The Open-Closed Principle, in review · Copeland, The Open/Close Principle is Confusing and, well, Wrong · InfoQ, Open-Closed Principle Challenged · Wikipedia, Liskov substitution principle · Martin, The Liskov Substitution Principle (C++ Report 1996) · Liskov and Wing, A Behavioral Notion of Subtyping (1994) · Hillel Wayne, The Liskov Substitution Principle · TypeScript Handbook, Object Types · Stack Overflow, Do Collections.unmodifiableXXX methods violate LSP? · Martin, The Interface Segregation Principle (C++ Report 1996) · Wikipedia, Interface segregation principle · abstractsoftware, a Xerox employee's objection · TypeScript Handbook, Type Compatibility · TypeScript Handbook, Utility Types · Go Proverbs · Copeland, ISP is Unhelpful but Inoffensive · dev.to, Passing entire objects as props · Martin, The Dependency Inversion Principle (C++ Report 1996) · Wikipedia, Dependency inversion principle · Shilkov, Interfaces Are Owned by High-level Modules · Fowler, Inversion of Control Containers and the Dependency Injection pattern · Embedded Artistry, DIP vs Dependency Injection · stripe-node · Stripe API, Create a PaymentIntent · chrisza4, Common misconception of dependency inversion · juststeveking, The interface with one implementation