Interface Segregation Principle

The principle, which we can translate as the interface separation principle, asks us to make logical distinctions within the interface. In short, it means forcing classes to implement methods that they will not use.

Let’s go with a real life example. I’ve seen a similar example somewhere, and I’ll go with a similar example;

public interface Animal{
    void run();
    void bark();
    void meow();
}

Here we have a class named animal and 3 methods in it called run, bark and meow. But there seems to be a problem as you can see.

public class Dog:Animal{
    void run{
        Console.WriteLine("Dog running");
    }

    void bark{
        Console.WriteLine("Dog barking");
    }

    void meow{
        // dogs don't meow 
    }
}

public class Cat:Animal{
    void run{
        Console.WriteLine("Cat running");
    }

    void bark{
        // Cats don't bark
    }

    void meow{
        Console.WriteLine("Cat meows");
    }
}

As you can see, cats can’t bark and dogs can’t meow, but it had to be implemented because it was defined in the interface. The Interface Segregation Principle says not to do this, but to do sensible interface partitioning/segregation. For example, it can be used like this:

public interface CanRun{
    void run();
}

public interface CanBark{
    void bark();
}

public interface CanMeow{
    void meow();
}

public class Dog:CanRun, CanBark{
    public void run(){
        Console.WriteLine("Dog running");
    }

    public void bark(){
        Console.WriteLine("Dog barking");
    }
}

public class Cat:CanRun, CanMeow{
    public void run(){
        Console.WriteLine("Cat running");
    }

    public void meow(){
        Console.WriteLine("Cat meows");
    }
}

As you can see, you don’t have to implement the process you didn’t do.

You may also like...