Interface Segregation Principle

Third principle states, that it is better to create some smaller interfaces, than one bigger – by doing that, we are getting rid of issues, where classes do not need method implementation of one big interface. Lets have a look at code below:

public interface IRaportable
{
    void PrintPdf();
    void PrintExcel();
}

public class SalaryRaport : IRaportable
{
    public void PrintPdf()
    {
        // print PDF file logic
    }

    public void PrintExcel()
    {
        // print CSV file logic
    }
}

public class HighSchoolExam : IRaportable
{
    public void PrintPdf()
    {
        // printing PDF
    }

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

We have created one Interface, which has two methods implemented. It would be fair to say, that it looks good – but it does not. Interface is although inherited by both of created classes, but each class does not implement a method as it should be. Here comes the question – why is that so crucial..? Lets assume that we have created a based typed List, through which we have to somehow iterate – in some cases there will be thrown an exception because of one thing – one class does not implement inherited method of an interface. In most cases in C# language, Interfaces implement max two methods, which beautifully gives an example of Interface Segregation Principle.

// split one interface to two smaller ones
public interface IPrintablePdf
{
    void PrintPdf();
}

public interface IPrintableExcel
{
    void PrintExcel();
}
// SalaryRaport inheritance from two interfaces
public class SalaryRaport : IPrintablePdf, IPrintableExcel
{
    public void PrintPdf()
    {
        // print PDF file logic
    }
    
    public void PrintExcel()
    {
        // print CSV file logic
    }
}

public class HighSchoolExam : IPrintablePdf
{
    public void PrintPdf()
    {
        // printing PDF
    }
}