Interface Segregation Principle
"Clients should not be forced to depend upon interfaces that they do not use."
In simple terms: It's better to have many small, specific interfaces than one large, general-purpose interface. Think of it like a restaurant menu: a vegetarian shouldn't be forced to hold a menu that only lists steak bundles.
Visualizing the Problem
Scenario: The "God" Interface
A SmartDevice interface requires Print, Fax, and Scan. See what happens when a simple printer tries to use it.
ISmartDevice
SimplePrinter
warning Violation! SimplePrinter is forced to implement Scan and Fax.
IPrinter
IFax
IScanner
SimplePrinter
check_circle Success! SimplePrinter only depends on what it uses.
cancel The "Fat" Approach
Imagine a Swiss Army Knife where you have to open all 50 blades just to use the toothpick. It's heavy, dangerous, and confusing. This is a violated interface.
check_circle The ISP Approach
ISP is like a well-organized toolbox. You pick only the tool you need. If you need a screwdriver, you don't carry the hammer and saw with you.
interface Worker { work(): void; eat(): void; sleep(): void; } // Human implements everything correctly class Human implements Worker { work() { console.log("Working..."); } eat() { console.log("Eating lunch..."); } sleep() { console.log("Zzz..."); } } // Robot is FORCED to implement methods it doesn't need! class Robot implements Worker { work() { console.log("Beep boop working..."); } // VIOLATION: Dummy code or exceptions eat() { throw new Error("Robots don't eat!"); } sleep() { throw new Error("Robots don't sleep!"); } }
quiz Check Your Understanding
1. You have an interface IBird with methods fly() and walk(). You create a Penguin class. Does implementing IBird violate ISP?
2. What is the main benefit of ISP?
Part of the SOLID Design Principles Series