🧩 What is the Interface Segregation Principle?
The Interface Segregation Principle (ISP) is one of the five SOLID principles of object-oriented programming. It helps developers avoid creating bloated interfaces that force classes to implement unnecessary members. ISP encourages the use of multiple, smaller interfaces tailored to specific client needs.
It aligns with the idea that no class should be forced to depend on methods it does not use.
🧱 A Misguided Interface Example
Imagine you are building an e-commerce platform. You define an IProduct
interface like this:
public interface IProduct
{
string Title { get; }
decimal Price { get; }
int Width { get; }
int Height { get; }
}
Now consider two implementations:
public class Television : IProduct
{
public string Title { get; set; }
public decimal Price { get; set; }
public int Width { get; set; }
public int Height { get; set; }
}
public class OnlineBook : IProduct
{
public string Title { get; set; }
public decimal Price { get; set; }
// These make no sense for an online book
public int Width { get; set; }
public int Height { get; set; }
}
This design forces the OnlineBook
class to implement properties that have no relevance to it. These unrelated members clutter the code and could lead to confusion or even bugs.
✅ Refactoring With ISP
To fix this, apply the Interface Segregation Principle by splitting the IProduct
interface into more focused contracts:
public interface IProduct
{
string Title { get; }
decimal Price { get; }
}
public interface IPhysicalProduct
{
int Width { get; }
int Height { get; }
}
Now each class implements only what it needs:
public class Television : IProduct, IPhysicalProduct
{
public string Title { get; set; }
public decimal Price { get; set; }
public int Width { get; set; }
public int Height { get; set; }
}
public class OnlineBook : IProduct
{
public string Title { get; set; }
public decimal Price { get; set; }
}
This makes the code cleaner and more accurate to the real-world objects being modeled.
🧠Key Takeaways
Avoid forcing classes to implement unused methods or properties
Favor small, specific interfaces over large general-purpose ones
ISP leads to better separation of concerns and easier maintenance
Clean interface design supports flexibility and scalability
📌 Summary
The Interface Segregation Principle is about respecting the boundaries of what a class should know or care about. It keeps your code modular and focused. When applied consistently, it reduces tight coupling and enhances the clarity and adaptability of your system.