Tuesday, May 2, 2023

SOLID - Interface Segregation Principle explanation with sample C# code

The Interface Segregation Principle (ISP) is a principle in object-oriented programming that states that clients should not be forced to depend on methods they do not use. In other words, an interface should only include methods that are relevant to the client that uses it.

Here is an example of how to implement the ISP in C#:
public interface IPrinter
{
    void Print(Document document);
}

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

public class Document
{
    public string Content { get; set; }
}

public class MultiFunctionPrinter : IPrinter, IScanner
{
    public void Print(Document document)
    {
        Console.WriteLine($"Printing {document.Content}");
    }

    public void Scan(Document document)
    {
        Console.WriteLine($"Scanning {document.Content}");
    }
}

public class SimplePrinter : IPrinter
{
    public void Print(Document document)
    {
        Console.WriteLine($"Printing {document.Content}");
    }
}
In this example, we have two interfaces, 'IPrinter' and 'IScanner', each with a single method relevant to their respective responsibilities. We also have a 'Document' class to represent a document.

We then have two printer classes, 'MultiFunctionPrinter' and 'SimplePrinter', that implement the 'IPrinter' interface. The 'MultiFunctionPrinter' class also implements the 'IScanner' interface.

By implementing the interfaces in this way, we are adhering to the ISP. The 'IPrinter' and 'IScanner' interfaces each have only one method that is relevant to their respective responsibilities. The 'MultiFunctionPrinter' class implements both interfaces because it has the capability to print and scan documents. The 'SimplePrinter' class only implements the 'IPrinter' interface because it doesn't have the capability to scan documents.

Overall, adhering to the ISP helps us create code that is more modular, easier to maintain, and more flexible. We can create interfaces that are specific to their responsibilities, and we can avoid bloated interfaces that force clients to depend on methods they do not use.

No comments:

Post a Comment