System Design ( Day - 39 )

Manoj KumarManoj Kumar
1 min read

SOLID Principles | Interface Segregation Principle

ISP ( Interface Segregation principle )
Many client specific interface are better than one general purpose interface, client should not be forced to implement methods they don’t need.

Like if the child class don’t need that method then it shouldn’t be forced to implement that method, that has to be flexible.
if that method is not related to that class then we have to create another abstract class for that method.

Decoupling: Large “fat” interfaces lead to implementing unused methods, creating unnecessary coupling.

Violation: A Printer interface:

interface Shape {
  area();
  volume();
}
class Square implements Shape {
  area() { … }
  volume() { /* unsupported */ } // this shouldn’t be here
}

Refactoring: Break into focused interfaces

interface TwoDimentionShape { area(); }
interface ThreeDimentionShape   { 
    area() ;
    volume(); 
}

class Rectangle implements TwoDimentionShape { area() { ... } }
class Cube implements ThreeDimentionShape { 
     area() { ... }
     volume() { ... }
 }

in the above example the implementation is segregated in two interfaces the TwoDimentionShape interface will be having only the implementation for 2D shapes, we are not forcing here anything.
the ThreeDimentionShape is having all the methods that has to be implemented.

Benefits

  • Clients depend only on the operations they actually need.

  • Smaller, clearer contracts.

0
Subscribe to my newsletter

Read articles from Manoj Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Manoj Kumar
Manoj Kumar