Track 04 · Lesson 6 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
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
| Device | print() | 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.
// 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
UserServicewith fifteen methods that every consumer depends on. - React props: a component that takes the whole
userobject 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