#42 SOLID - Interface Segregation Principle
Introduction
We have already introduced the first three principles of SOLID, and now let's begin with the I - Interface Segregation Principle.
To revise the Liskov substitution principle, go here.
Interface Segregation Principle (ISP)
No code should be forced to depend on methods it does not use
This principle is quite stright forward which means you should not put all the methods you need to a single interface. Splits to different interfaces.
Let us keep using the Shape interface that we previously created while introduce Open-closed principle with further explanation. The naming maybe a little confusing, so lets rephrase it as 2DShape.
public interface 2DShape {
public int sum();
public int area(); // relevant
public int volume(); // irrelevant
}
We add two new functions to 2DShape this time, area()
and volume()
. It is good to have area()
in 2DShape interface for calculate 2D area. Now assume that we want to extend our program to support 3D shapes and add volume()
method for volume calculation.
We clearly know that a 2D shape have no volume. You may already have the answer, volume()
should be seperated and implemented in an interface call 3DShape.
ISP may look simple but vary important when handling a large-scale project. It can keep the project decoupled which easier to change, refactor and have further updates.
That is all about the Interface Segregation Principle and we will introduce the last principle of SOLID in the next article.
Discussion