Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 

README.md

Interface Segregation Principle (ISP)

📖 What is ISP?

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.


❌ Before (ISP Violation)

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.


✅ After (ISP Followed)

The large interface is divided into smaller, focused interfaces.

  • Cook
  • Serve
  • Billing

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.


📂 Project Structure

d_ISP
│
├── before/
│   └── ISP Violation
│
├── after/
│   └── ISP Implementation
│
└── README.md

🎯 Benefits of ISP

  • Smaller and focused interfaces
  • Cleaner class design
  • Easier to maintain
  • Better flexibility
  • Reduces unnecessary code

💡 Real-World Example

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.


🤔 LSP vs ISP

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

🚀 Key Takeaway

Don't force a class to implement methods it doesn't need.