EI as Eexrcises of Interface segregation principle

By | March 9, 2020

Interface segregation principle

Many small and dedicated interfaces are better than few and general.

Hot to use ISP in practice?

You should separate the interfaces into smaller interfaces and better design of abstract elements in the application. The best place for a division is taking the Single Responsibility Principle. Each area should have one reason to change. It should reduce dependencies and increase consistency. Interfaces should contain such a set of methods that classes implementing them do not have to implement methods they do not want to implement.

Example

class Program
  {
      static void Main(string[] args)
      {
          IDataImporter reportImporter = new ReportImporter();
          Console.WriteLine(reportImporter.GetDataFromPdf());
          Console.WriteLine(reportImporter.GetDataFromExcel());
 
          IDataImporter pictureImporter = new TableImporter();
          Console.WriteLine(pictureImporter.GetDataFromPdf());
          Console.WriteLine(pictureImporter.GetDataFromExcel());
      }
  }
 
  internal class TableImporter : IDataImporter
  {
      public string GetDataFromExcel()
      {
          return "Table from Excel";
      }
 
      public string GetDataFromPdf()
      {
          //We do not return a table from pdf file
          return string.Empty;
      }
  }
 
  internal class ReportImporter : IDataImporter
  {
      public string GetDataFromExcel()
      {
          return "Report from Excel";
      }
 
      public string GetDataFromPdf()
      {
          return "Report from Pdf";
      }
  }
 
  internal interface IDataImporter
  {
      string GetDataFromExcel();
      string GetDataFromPdf();
  }

Class TableImporter implements a method, which is not using. It is better, to separate interface DatImporter to smaller interfaces. Then all classes will implement what they need.

class Program
{
    static void Main(string[] args)
    {
        var reportImporter = new ReportImporter();
        Console.WriteLine(reportImporter.GetDataFromPdf());
        Console.WriteLine(reportImporter.GetDataFromExcel());
 
        IExcelParser pictureImporter = new TableImporter();
        Console.WriteLine(pictureImporter.GetDataFromExcel());
    }
}
 
internal class TableImporter : IExcelParser
{
    public string GetDataFromExcel()
    {
        return "Table from Excel";
    }
}
 
internal class ReportImporter : IExcelParser, IPdfParser
{
    public string GetDataFromExcel()
    {
        return "Report from Excel";
    }
 
    public string GetDataFromPdf()
    {
        return "Report from Pdf";
    }
}
internal interface IExcelParser
{
    string GetDataFromExcel();
}
internal interface IPdfParser
{
    string GetDataFromPdf();
}

All posts from mini project: Learn SOLID and OOP principles:

Sources

Main image

Materials

Leave a Reply

Your email address will not be published. Required fields are marked *