The Interface Segregation Principle (ISP) states:
Clients should not be forced to depend on interfaces they do not use.
In simple words:
Create small, specific interfaces instead of one large interface.
A single RestaurantWorker interface contains multiple methods:
cook()serveCustomer()generateBill()cleanTable()
Every employee (Chef, Waiter, Cashier) is forced to implement all these methods, even if they don't need them.
For example:
- 👨🍳 Chef doesn't generate bills.
- 💵 Cashier doesn't cook.
- 🍽 Waiter doesn't cook.
This leads to unnecessary or empty method implementations.
The large interface is divided into smaller, focused interfaces.
CookServeBilling
Now each class implements only the interfaces it actually needs.
- 👨🍳 Chef →
Cook - 🍽 Waiter →
taking order, Serve - 💵 Cashier →
Billing
Each class has only the required responsibilities.
d_ISP
│
├── before/
│ └── ISP Violation
│
├── after/
│ └── ISP Implementation
│
└── README.md
- Smaller and focused interfaces
- Cleaner class design
- Easier to maintain
- Better flexibility
- Reduces unnecessary code
Think of a restaurant.
Different employees have different responsibilities.
- 👨🍳 Chef → Cooks food
- 🍽 Waiter → Serves customers and cleans tables
- 💵 Cashier → Generates bills
Instead of making every employee perform every task, each employee only implements the responsibilities required for their role.
These two principles are often confused, but they solve different problems.
| LSP (Liskov Substitution Principle) | ISP (Interface Segregation Principle) |
|---|---|
| Focuses on inheritance | Focuses on interfaces |
| Child classes should correctly replace parent classes | Classes should implement only the interfaces they need |
| Prevents incorrect inheritance | Prevents "fat" or large interfaces |
Example: Bicycle should not extend an engine-powered Vehicle |
Example: Chef should not implement generateBill() |
| Goal: Correct behavior in inheritance | Goal: Small, focused interfaces |
Don't force a class to implement methods it doesn't need.