This Angular tutorial helps you get started with Angular quickly and effectively through many practical examples.

Interface Segregation Principle (ISP)


In this article we are going to discuss Interface Segregation Principle (ISP) in C#. There are many blogs, articles are available on the internet regarding Interface Segregation Principle (ISP) but in this particular article I will try to explain to you with as much as simple.

Interface Segregation Principle (ISP)

The Interface Segregation Principle (ISP) is one of the five SOLID principles of object-oriented design. In simpler terms, it suggests that it's better to have many small, specific interfaces rather than one large, general-purpose interface.

In C#, this can be implemented by defining multiple smaller interfaces for different functionalities rather than a single large interface. Here's an example to illustrate this:

Suppose you have a Printer class that can print, scan, and fax documents. Rather than having a single interface with all these methods, you can split them into separate interfaces.

Without Interface Segregation Principle

In this example, OldPrinter has to implement the Scan and Fax methods even though it doesn't support those functionalities. This violates the ISP.

Interface Segregation Principal in C#

Example

public interface IPrinter
{
    void Print(Document document);
    void Scan(Document document);
    void Fax(Document document);
}

public class MultiFunctionPrinter : IPrinter
{
    public void Print(Document document) { /* implementation */ }
    public void Scan(Document document) { /* implementation */ }
    public void Fax(Document document) { /* implementation */ }
}

public class OldPrinter : IPrinter
{
    public void Print(Document document) { /* implementation */ }
    public void Scan(Document document) { /* implementation */ } // Not supported
    public void Fax(Document document) { /* implementation */ } // Not supported
}

With Interface Segregation Principle

Here, the interfaces are split into IPrinter, IScanner, and IFax. Now, OldPrinter only needs to implement the IPrinter interface and isn't forced to implement methods it doesn't support. This adheres to the Interface Segregation Principle, making the code cleaner, more maintainable, and more flexible.

public interface IPrinter
{
    void Print(Document document);
}

public interface IScanner
{
    void Scan(Document document);
}

public interface IFax
{
    void Fax(Document document);
}

public class MultiFunctionPrinter : IPrinter, IScanner, IFax
{
    public void Print(Document document) { /* implementation */ }
    public void Scan(Document document) { /* implementation */ }
    public void Fax(Document document) { /* implementation */ }
}

public class OldPrinter : IPrinter
{
    public void Print(Document document) { /* implementation */ }
}

Prev Next