DEV Community

loading...

Interface Segregation Principle

Eduardo Julião
Software Developer | Geek since 1993 | @monsieurxuxu on twitter
・1 min read

The Interface Segregation Principle (ISP) states:

A client should not implement interfaces that are not necessary for the application.

In other words, it's preferably that instead of one big interface, the developer creates smaller more manageable interfaces.

Let's say we're tasked to create a game about robots, at first, we design our interface:

public interface IRobot
{
    string Name { get; set; }
    void Walk();
    void Fly();
    void Attack();
}
Enter fullscreen mode Exit fullscreen mode

Perfect! We created our contract for what makes a robot... that violates the Interface Segregation Principle, because not all robots can Walk, Fly or Attack.

public class FriendlyRobot : IRobot
{
    public string Name { get; set; }

    public void Walk()
    {
        // Code
    }

    public void Fly()
    {
        Console.WriteLine("This robot can't fly!");
    }

    public void Attack()
    {
        Console.WriteLine("This robot can't attack!");
    }
}
Enter fullscreen mode Exit fullscreen mode

To solve this issue, we need to break down into smaller interfaces:

public interface IRobot
{
    string Name { get; set; }
}

public interface IWalkable
{
    void Walk();
}

public interface IFlyable
{
    void Fly();
}

public interface IAggressive
{
    void Attack();
}
Enter fullscreen mode Exit fullscreen mode

Now we can create a Robot the way we want, without implementing extra code that's not necessary, so our FriendlyRobot will be implemented in a different way:

public class FriendlyRobot : IRobot, IWalkable
{
    public string Name { get; set; }

    public void Walk()
    {
        // Code
    }
}
Enter fullscreen mode Exit fullscreen mode

Discussion (0)