Interface Segregation Principle In Typescript

Hasan Zohdy
Oct 15, 2023
2 min read
post_comment1 Comments
post_like0 Likes

#Introduction

Interface Segregation Principleis the 4th principle ofSOLIDprinciples. It is also known asISPprinciple. It was first introduced byRobert C. Martinin his 2000 paperDesign Principles and Design Patterns.

#Definition

The concept is simple, make the interfaces smaller and more specific to the use case. it is better to have multiple but smaller interfaces than a single large interface.

So basically, a class should not be forced to implement an interface or methods that it does not use.

#Key Concepts Of ISP

  • Cohesion: Interfaces should be highly cohesive. It means the interface methods should be related to each other, if they are not related then they should be separated into different interfaces.
  • Responsibility: Interfaces should have single responsibility.

#Example

Let's take an example of aPrinterclass that can print, scan and fax. So we can create an interfaceMultiFunctionPrinterthat has all the methods ofPrinterclass.

interface MultiFunctionPrinter {
  print(): void;
  scan(): void;
  fax(): void;
}

Now we have aSimplePrinterclass that can only print. So we can implement theMultiFunctionPrinterinterface inSimplePrinterclass.

class SimplePrinter implements MultiFunctionPrinter {
  print(): void {
    console.log("Printing...");
  }
  scan(): void {
    throw new Error("Simple Printer can not scan.");
  }
  fax(): void {
    throw new Error("Simple Printer can not fax.");
  }
}

This is a total violation ofISPprinciple. BecauseSimplePrinterclass is forced to implement thescanandfaxmethods that it does not use.

#Solution

To make this run smoothly, we can separate the interface into three different interfaces.

interface Printer {
  print(): void;
}

interface Scanner {
  scan(): void;
}

interface Fax {
  fax(): void;
}

Now we can implement the interfaces inSimplePrinterclass.

class SimplePrinter implements Printer {
  print(): void {
    console.log("Printing...");
  }
}

If there is advanced printer class, it can implement multiple interfaces.

class AdvancedPrinter implements Printer, Scanner, Fax {
  print(): void {
    console.log("Printing...");
  }
  scan(): void {
    console.log("Scanning...");
  }
  fax(): void {
    console.log("Faxing...");
  }
}

#Conclusion

ISPprinciple is very important to make the code more maintainable and flexible. It also helps to reduce the coupling between classes and not implementing unnecessary methods.

You are not logged in.