Track 04 · Lesson 5 of 15Code that stays easy to change

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.

storage.tsWithout it
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 runtime

The 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

A Penguin class extends Bird and its fly() throws. What's the Liskov-friendly fix?