ISP principle


Interface Segregation Principle states:

“A client should never be forced to implement an interface that it doesn’t use, or clients shouldn’t be forced to depend on methods they do not use.”

It is a very powerful principle. Why? Because it forces a good design. In this post, we see what an ISP is, and in the next posts, we will see the negative and positive consequences of ISP.

Let’s see some example. We have requirements to transport people and small packages. The interface can look like:

interface Transport {
  transport (Point A, Point B, int peopleCount)
  transport (Point A, Point B, List<Package> packages)
}

When comes to implementation:

Van implements Transport {
  transport (Point A, Point B, int peopleCount) {...}
  transport (Point A, Point B, List<Package> packages) {...}
}

This implementation is compliant with the ISP principle because Van uses/implements all the Transport interface methods.

Then we have other requirements. The Car can transport people, but not packages:

Car implements Transport {
  transport (Point A, Point B, int peopleCount) {...}
  transport (Point A, Point B, List<Package> packages) {throw UnsupportedOperationException}
}

The Parcelobus can transport Packages but not people:

Parcelobus implements Transport {
  transport (Point A, Point B, int peopleCount) {throw UnsupportedOperationException}
  transport (Point A, Point B, List<Package> packages) {...}
}

Oh, not good. Car and Parcelobus are not compliant with ISP principles, because they do not use/implement all the methods from the Transport interface.

You can say: no big deal. Yes, it is no big deal now, but let’s see what the code will look like.


Leave a Reply

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