Today, let's talk about a simple way to make your C# code cleaner and easier to manage—the Interface Segregation Principle (ISP).
What is the Interface Segregation Principle?
The Interface Segregation Principle (ISP) means:
"A class should not be forced to implement methods it doesn’t need."
In simple words, don’t create big interfaces that make classes do things they don’t need to do. Instead, split them into smaller, more specific ones.
Why is ISP Important?
If we don’t follow ISP, our code becomes:
- Hard to maintain – We add unnecessary methods to classes.
- Less flexible – A simple change can break multiple classes.
- More complicated – Too many unused methods make the code confusing.
Let’s see a real example!
Bad Example (Violating ISP)
Imagine we are designing a system for humans and robots in a workplace. We create a general interface for all workers:
public interface IWorker
{
void Work();
void Eat();
void Sleep();
}
Now, let’s implement it:
public class HumanWorker : IWorker
{
public void Work() { Console.WriteLine("Human is working."); }
public void Eat() { Console.WriteLine("Human is eating."); }
public void Sleep() { Console.WriteLine("Human is sleeping."); }
}
public class RobotWorker : IWorker
{
public void Work() { Console.WriteLine("Robot is working."); }
public void Eat() { throw new NotImplementedException(); } // Robots don’t eat
public void Sleep() { throw new NotImplementedException(); } // Robots don’t sleep
}
What’s Wrong?
-
RobotWorker
has to implementEat()
andSleep()
, even though robots don’t need them. - The interface mixes unrelated actions (working, eating, sleeping) into one.
- If we add a new worker type, it might need to implement unnecessary methods too.
Good Example (Following ISP)
Let’s fix this by creating separate interfaces:
public interface IWorkable
{
void Work();
}
public interface IHumanNeeds
{
void Eat();
void Sleep();
}
Now, let’s implement them properly:
public class HumanWorker : IWorkable, IHumanNeeds
{
public void Work() { Console.WriteLine("Human is working."); }
public void Eat() { Console.WriteLine("Human is eating."); }
public void Sleep() { Console.WriteLine("Human is sleeping."); }
}
public class RobotWorker : IWorkable
{
public void Work() { Console.WriteLine("Robot is working."); }
}
Why is this better?
✅ HumanWorker
implements only what it needs, both Work()
and human-specific actions like Eat()
and Sleep()
.
✅ RobotWorker
only implements Work()
, no extra methods.
✅ We follow ISP properly by breaking the big interface into smaller, focused ones.
Final Thoughts
By following ISP, we get:
- Cleaner code – No unnecessary methods.
- Easier maintenance – Changes won’t affect unrelated classes.
- Better flexibility – We can add new features without breaking the existing code.
Next time you design an interface, ask yourself: “Am I forcing a class to implement something it doesn’t need?” If yes, split the interface into smaller parts!
Happy coding!
Find me on LinkedIn
Top comments (0)