Interface Segregation Principle

Interface Segregation Principle

Many client-specific interfaces are better than one general-purpose interface. means One big interface needs to split into many smaller and relevant interfaces.

1. No class should be forced to depend on methods it does not use.

Example

We create an interface that performs Printer-related tasks.

namespace Solid_principle
{
    interface IPrinter
    {
        bool Print(string content);
        bool Scan(string content);
        bool Fax(string content);
    }
}

Now suppose we have Printer A that implements IPrinter Interface.

namespace ISPExplantion
{
    class Printer_A : IPrinter
    {
        public bool Print(string content)
        {
            Console.WriteLine("Print Success");
            return true;
        }
        public bool Scan(string content)
        {
            Console.WriteLine("Scan Success");
            return true;
        }
        public bool Fax(string content)
        {
            Console.WriteLine("Fax Success");
            return true;
        }

    }
}

It is ok for printer A, but suppose we have another printer B that can only perform Print scans but does not have the functionality to fax.

namespace ISPExplantion
{
    class Printer_B : IPrinter
    {
        public bool Print(string content)
        {
            Console.WriteLine("Print Success");
            return true;
        }
        public bool Scan(string content)
        {
            Console.WriteLine("Scan Success");
            return true;
        }
        public bool Fax(string content)
        {
            //Cannot implement mehod as printer do not have functionality.
        }

    }
}

In this scenario, we cannot implement all the methods of the IPrinter Interface, and ISP tells us that no method should be used in class that it does not use.

This problem can be solved by segregating one big Interface (IPrinter) into smaller interfaces.

namespace Solid_principle
{
    interface IPrinter
    {
        bool Print(string content);
        bool Scan(string content);
    }
    interface IFaxData
    {
        bool Fax(string content);
    }
}

So, we have segregated the related methods into smaller interfaces that are relevant for the purpose.

Every printer has print and scan functionality, and some advanced printers can fax; hence, those methods are separated into different interfaces.

So instead of having a big interface, it is better to split that interface into smaller and relevant interfaces.


Similar Articles