lesson 4/5 · 0:54
Interface Segregation Principle
Why a class that only bakes can break when delivery changes, and how splitting one fat interface fixes it.
“No client should be forced to depend on methods it does not use.”
The story
Tony gives every hire the same form, so Maria, who only bakes, signs for driving too.
The problem in code
One Worker interface with bake, deliver and payBills. Maria’s class only bakes, so the other methods are empty. Product asks drivers to share their location, you add track to Worker, and Maria’s class stops compiling for a job it never does.
interface Worker {
bake(order: Order): void;
deliver(order: Order): void;
payBills(): void;
track(): Location; // new: now every Worker must implement it
}
class Maria implements Worker {
bake(order: Order) { /* the only real job */ }
deliver() {}
payBills() {}
// compile error: missing track()
}
The fix
Split the form into Baker, Driver and Bookkeeper. Each class implements only what it does, so track lands only in Driver.
interface Baker { bake(order: Order): void }
interface Driver { deliver(order: Order): void; track(): Location }
interface Bookkeeper { payBills(): void }
class Maria implements Baker {
bake(order: Order) { /* ... */ }
}
Takeaway
Empty methods and throw new Error('not supported') are signs an interface is too big. Shape interfaces around what each client needs.