Interface Segregation Principle
The ‘I’ in SOLID design principles is for the Interface Segregation Principle. The gist of it is that clients should not be forced to implement interfaces they don’t use. In other words, create interfaces that serve the client’s needs, instead of creating one general-purpose interface that attempts to serve all possible clients.
This promotes the use of smaller, more focused interfaces which can be easier to understand and implement.
In keeping with our zoo example, pretend we’re building a management system which would help the zookeepers in their day-to-day jobs. We would need those working with mammals to feed and walk the animals but fish don’t need to go for walks.
// Interface for animals that need to be fed (hopefully all of them)
interface IFeedable
{
void Feed();
}
// Interface for animals that need to be walked
interface IWalkable
{
void Walk();
}
// Base class for mammals
class Mammal : IFeedable, IWalkable
{
public void Feed()
{
// code to feed the mammal
}
public void Walk()
{
// code to walk the mammal
}
}
// Base class for fish
class Fish : IFeedable
{
public void Feed()
{
// code to feed the fish
}
}
In this simplified example, we can already see how the code is more readable and easier to understand.