DEV Community

Eduardo Julião
Eduardo Julião

Posted on

2 1

Interface Segregation Principle

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

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay