SOLID Principles Demystified — (I)
Interface Segregation Principle
Interfaces must not force classes to implement functionality that they do not support, meaning larger interfaces should be split into smaller ones to offer support.
Sample Scenario
Let’s use the same scenario with the AreaCalculator class and add new functionality to it. This time the user would like the sum of the volume of shapes like Cube, Cuboid and etc.
Poorly Written
Any shape you create must implement the volume method, but you know that squares are flat shapes and that they do not have volumes, so this interface would force the Square class to implement a method that it has no use of.
This violates the Interface Segregation Principle.
Well Written
To remedy this violation, we must create a new interface called IShape3D to handle shapes that has a volume and keep IShape interface as it it to handle 2D shapes.
Major Benefits
- High cohesion — better understandability, robustness.
- Low coupling — better maintainability, high resistance to changes.
- Classes are not forced to implement interfaces that they do not use.