The Interface Segregation Principle (ISP) states that:
Clients should not be forced to depend on interfaces they do not use.
In other words, interfaces should be minimal and specific to the functionality required by the clients using them. This allows minimizing dependencies between modules and makes the system more easily extensible and modifiable.
Violation of the principle
Imagine having an application for managing animals in a zoo. We could have an interface called IAnimal
that includes all possible operations for animals in the zoo:
public interface IAnimal
{
void Eat();
void Sleep();
void Swim();
void Fly();
}
Now, let's suppose we have a Penguin
class that implements the IAnimal
interface:
public class Penguin : IAnimal
{
public void Eat()
{
// Method implementation
}
public void Sleep()
{
// Method implementation
}
public void Swim()
{
// Method implementation
}
public void Fly()
{
throw new NotImplementedException("Penguins cannot fly");
}
}
In this example, the Interface Segregation Principle is violated because the Penguin
class is forced to implement the Fly
method, even though penguins do not fly.
Application of the principle
To resolve the violation of the Interface Segregation Principle, we can break down the IAnimal
interface into smaller and more specific interfaces:
public interface IEating
{
void Eat();
}
public interface ISleeping
{
void Sleep();
}
public interface ISwimming
{
void Swim();
}
public interface IFlying
{
void Fly();
}
Now, the Penguin
class can implement only the relevant interfaces for its functionality:
public class Penguin : IEating, ISleeping, ISwimming
{
public void Eat()
{
// Method implementation
}
public void Sleep()
{
// Method implementation
}
public void Swim()
{
// Method implementation
}
}
In this way, the code is cleaner, more flexible, and easily maintainable, because the classes implement only the interfaces strictly necessary for their functionality.
Conclusion
In this article, we have delved into the Interface Segregation Principle, which teaches us to create small and specific interfaces that expose only the functionalities required by the clients using them, avoiding the creation of 'monolithic' interfaces that include all functionalities, regardless of their use by clients. Additionally, it guides us in designing classes that implement only the interfaces strictly relevant to their functionality, minimizing dependencies between modules and facilitating code maintenance.
Top comments (0)