Track 04 · Lesson 5 of 15Code that stays easy to change
- 01Principles at a glance
- 02SOLID principles at a glance
- 03S: Single responsibility
- 04O: Open/closed
- 05L: Liskov substitution
- 06I: Interface segregation
- 07D: Dependency inversion
- 08Separation of concerns
- 09DRY: Don't repeat yourself
- 10KISS: Keep it simple
- 11YAGNI: You aren't gonna need it
- 12Composition over configuration
- 13Fail fast
- 14Least surprise
- 15When they disagree
Track 04 · Code that stays easy to change
L: Liskov substitution
Lesson 5 of 15· 7 min
If code works with a type, it must keep working with any subtype of it. A subclass that throws, does nothing, or quietly does less than its parent breaks every caller that trusted the parent. It’s the L in SOLID, named after Barbara Liskov.
Plug in a store
Try all four, then flip the switch
saveDraft(store) was written for any store. Plug one in.
ReadOnlyStore: a snapshot you can’t write to
A subtype must work anywhere its parent does. Try the last two stores.
class Store {
get(key: string): string | null { /* … */ }
save(key: string, value: string): void { /* … */ }
}
// "It's a Store too, just one you can't write to"
class ReadOnlyStore extends Store {
save(): void {
throw new Error("Read-only!") // breaks the parent's promise
}
}
// Written for Store. Works for every Store… except this one.
function saveDraft(store: Store, text: string) {
store.save("draft", text)
}
saveDraft(new ReadOnlyStore(), "Hello") // 💥 at runtimeThe warning signs#
A subtype breaks the promise when it:
- throws on a method the parent supports (“not supported”),
- silently does nothing, or does less (drops data, ignores an option),
- demands more than the parent did (stricter inputs) or returns less (weaker guarantees).
The classic textbook case is Square extends Rectangle: set the width to 4 and the height to 5, and a square turns into 5 × 5. Code written for rectangles expected 20, and got 25.
The fix is usually a smaller promise#
If something can’t keep the whole contract, it shouldn’t claim it. Split the interface (ReadableStore and WritableStore) so each type promises only what it can do, and let the type checker refuse the mistake while you’re typing. Prefer “has a” over “is a” when the fit is awkward.
Check yourself