principletypescriptModerate
SOLID — Interface Segregation Principle: Clients Should Not Depend on Unused Methods
Viewed 0 times
interface segregationISPSOLIDfat interfacerole interfacesdependency on unused methods
Problem
A fat interface forces implementors to provide methods they do not use. A class implementing
IWorker with both work() and eat() must implement eat() even if it is a Robot that doesn't eat.Solution
Split large interfaces into smaller, focused ones. Clients depend only on the interfaces they use.
// Bad: fat interface
interface IWorker {
work(): void;
eat(): void;
sleep(): void;
}
// Robot must implement eat() and sleep() with stubs — violation
// Good: segregated interfaces
interface IWorkable { work(): void; }
interface IFeedable { eat(): void; }
interface ISleepable { sleep(): void; }
class Human implements IWorkable, IFeedable, ISleepable {
work() { console.log('working'); }
eat() { console.log('eating'); }
sleep() { console.log('sleeping'); }
}
class Robot implements IWorkable {
work() { console.log('robot working'); }
// no eat() or sleep() required
}
// A function that only needs work() depends only on IWorkable
function manage(worker: IWorkable) { worker.work(); }
manage(new Robot()); // no problemWhy
ISP reduces coupling: a change to
IFeedable does not require recompiling or retesting robots. It also prevents forcing stub implementations that violate LSP.Gotchas
- In TypeScript, structural typing means you rarely need to explicitly declare
implements— a type that has the required shape satisfies the interface. ISP is still useful for clarity. - Don't over-segregate: one method per interface leads to role-interface hell. Group methods that are always used together.
- ISP and SRP are complementary: SRP tells you a class should have one reason to change; ISP tells you an interface should serve a specific client role.
Revisions (0)
No revisions yet.