Interface Segregation Principle
ISP
“Clients should not be forced to depend upon interfaces that they do not use.” – Robert C. Martin
It is better to have many small, specific interfaces than one large, general-purpose interface.
When to use
When you have “fat” interfaces that have methods for unrelated clients.
Why it matters
- Decoupling: Changes to a method in a large interface don’t affect clients that don’t even use that method.
- Clarity: Interfaces describe exactly what a client needs, nothing more.
Signs of Violation
- You implement an interface and leave half the methods empty or throwing errors.
- A class depends on a massive
Serviceinterface just to use one method.
Explanation
Problem
A Fat Interface causes coupling between clients that otherwise have nothing in common. If Client A needs methodA() and Client B needs methodB(), and both methods are in InterfaceI, then changes to methodB might force a recompile/redeploy of Client A.
Solution
Break the interface down into smaller partial interfaces (Role Interfaces). Classes can implement multiple interfaces if needed.
Real world analogy
A Swiss Army Knife has many tools. If you only need a knife, carrying the corkscrew, scissors, and saw is unnecessary weight. It’s better to have a specialized tool for the job.
Pros and Cons
| Pros | Cons |
|---|---|
Comparison
- SRP: SRP is about the class implementation; ISP is about the interface definition.
Code example
Typescript
Bad (Violation)
Good (Adherence)
PHP
Bad (Violation)
Good (Adherence)