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

Track 04 · Code that stays easy to change

I: Interface segregation

Lesson 6 of 15· 6 min

No code should be forced to depend on methods it doesn’t use. Big interfaces make implementers fake abilities they don’t have, and make every caller and every test drag along methods they never call. It’s the I in SOLID.

Fax the contract

Pick a device, then flip the switch

Deviceprint()scan()fax()staple()
Office hub✓ real✓ real✓ real✓ real
Basic printer✓ real✕ throws✕ throws✕ throws
Phone scanner app✕ throws✓ real✕ throws✕ throws

The “Fax this contract to…” menu

6

Fake methods that only throw

4

Methods a test must fake to check printing

Pick a device from the fax menu.

devices.tsWithout it
// One interface for every office device
interface OfficeDevice {
  print(doc: Doc): void
  scan(): Image
  fax(doc: Doc, to: string): void
  staple(doc: Doc): void
}

class BasicPrinter implements OfficeDevice {
  print(doc: Doc) { /* real */ }
  scan(): Image { throw new Error("Can't scan") }
  fax() { throw new Error("Can't fax") }
  staple() { throw new Error("Can't staple") }
}

// The UI lists every OfficeDevice under "Fax to…"
devices.forEach((d) => menu.add(d.name, () => d.fax(contract, "+44…")))

It shows up everywhere#

  • Interfaces and classes: a UserService with fifteen methods that every consumer depends on.
  • React props: a component that takes the whole user object when it only shows the avatar, so every test builds a full user.
  • Tests: to test one thing, you fake ten methods nobody calls.

Ask for the ability, not the bundle#

Split by what callers need: Printer, Scanner, Fax; UserReader and UserWriter. A class can still implement several. Functions then ask for exactly what they use, which makes them honest about their dependencies and trivially easy to test.

Check yourself

A component only shows a user's avatar but takes the whole User object. What's the downside?