Interface Segregation Principle (ISP) – S.O.L.I.D. Framework

Frameworks Mar 21, 2017

The fourth principle of the S.O.L.I.D. Framework is the Interface Segregation Principle (ISP) .

The main statement of this principle is “clients should not be forced to implement interfaces they don’t use“.

This basically means that any software developer should use very short and small interfaces instead of one big ones. In the following example I demonstrate the usage of this principle. We have an interface defintion for Car which provides an Accelerate(), ShiftDown() amd ShiftUp() method.

If we are now implementing a Car with the ICar interface everyhting seems fine, but if we are thinking about an Electric Car implementation which does not have a ShiftUp() and ShiftDown() method we are running into a problem. We suddenly need to implement methods which are useless for our purpose and which increase the confusion level unnecessary. Futhermore with this implementation we violate the Interface Segregation Principle.

public interface ICar
{
    void Accelerate();

    void ShiftUp();

    void ShiftDown();
}

public class Car : ICar
{
    private int speed { get; set; }
    private int gear { get; set; }

    public void Accelerate()
    {
        this.speed++;
    }

    public void ShiftDown()
    {
        this.gear--;
    }

    public void ShiftUp()
    {
        this.gear++;
    }
}

public class ElectricCar : ICar
{
    private int speed { get; set; }

    public void Accelerate()
    {
        speed++;
    }

    public void ShiftDown()
    {
        throw new NotImplementedException();
    }

    public void ShiftUp()
    {
        throw new NotImplementedException();
    }
}

The solution to match the defintion of the Interface Segregation Principle would be to split up to multiple interfaces like in the following example.

public interface IAccelerateable
{
    void Accelerate();
}

public interface IShiftable
{
    void ShiftUp();

    void ShiftDown();
}

public class Car : IAccelerateable, IShiftable
{
    private int speed { get; set; }
    private int gear { get; set; }

    public void Accelerate()
    {
        this.speed++;
    }

    public void ShiftDown()
    {
        this.gear--;
    }

    public void ShiftUp()
    {
        this.gear++;
    }
}

public class ElectricCar : IAccelerateable
{
    private int speed { get; set; }

    public void Accelerate()
    {
        speed++;
    }
}

Now our Electric Car implementation has only to implement the IAccelerateable interface and not the IShiftable interface. This is what the ISP is all about.

Tags

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.