π‘ What is Interface Segregation Principle (ISP)?
The ISP, part of the SOLID principles, states:
"A client should not be forced to depend on methods it does not use."
When an interface has too many unrelated methods, classes implementing it may end up with unnecessary or unused code, leading to fragile, hard-to-maintain systems.
ISP encourages creating smaller, more specific interfaces to keep things clean and manageable.
π― Simple Example
Imagine youβre ordering from a restaurant with a menu full of dishes you donβt like. You have to flip through 30 pages of irrelevant options to find it. Frustrating, right?
What if there were focused, specialized menus β one for sandwiches, one for sushi, one for desserts? Suddenly, ordering becomes becomes easier. This is exactly what ISP suggests:
π« No massive, one-size-fits-all interfaces full of unused methods.
β Small, specific interfaces tailored to fit the needs of their users.
Code Example
π Benefits
β No more unnecessary methods: Each class gets exactly what it needs, nothing more.
β Easier to understand, maintain and extend.
β Cleaner design: No more empty or "not supported" methods.
β οΈ Signs of Violations
β Large Interfaces
β Unimplemented Methods
π‘ How to Avoid ISP Violations
β
Refactor Large Interfaces into smaller, more specialized ones.
β
Implement Only Whatβs Needed β classes should only implement methods relevant to their behavior.
β
Focus on Composition, not inheritance, so your code stays flexible and easier to extend without violating ISP.
π° Others
Interested? π Check out other posts from my programming principles series!
- Liskov Substitution Principle (LSP) Explained in 100 Seconds
- KISS Design Principle Explained in 100 Seconds
- DRY Principle Explained in 100 Seconds
- "Tell, Don't Ask" Principle Explained in 100 Seconds
- Golang Dependency Injection - Just in 5 Minutes!
Follow me to stay updated with my future posts:
Top comments (0)