Photo by Blue Bird

SOLID: Interface Segregation Principle

Paul Allies
2 min readJul 7, 2022

All programs are composed of functions and data structures. The SOLID principles introduced by Robert C. Martin, help us group our code into modules and advise how to interconnect them. The whole point of application architecture is to manage change. Software requirements change all the time and we as developers need to ensure that these changes don’t break existing code.

There are 5 principles that make up the acronym are:

In this post, I will attempt to explain the ISP (Interface Segregation Principle).

Within OOP, interfaces provide layers of abstraction that allows the program to depend on the interface rather than the implementation.

The ISP (Interface Segregation Principle) states:

Clients should not be forced to depend upon interfaces that they do not use

As your application grows you are tempted to add methods to an existing interface. If the methods are not related to the interface, it is better to separate that new method out into its own interface

Just as the SRP advises to streamline your classes for a single purpose, so too does the ISP guide you to split your interfaces into parts of relevance to reduce the effect of change on the application.

Just like the Liskov Substitution Principle, reasonable indications of violating ISP are:

  • Our methods return inappropriate data
  • Our methods have to throw “not implemented” exceptions

This will make it difficult to write effective code against these interfaces.

To fix this we need to segregate the interface into sub-interfaces so that none of the classes will be forced to write inappropriate implementation methods

Let’s explain using some code:

OUTPUT:
Helicopter Flying...
Car Moving...

Note the methods in classes that are not implemented and hence the ISP is violated.

To fix this problem we can break out the common methods into a base interface and group related methods into sub-interfaces of the base.

OUTPUT:
Helicopter Flying...
Car Moving...

We still have the same output, but our code is more robust. We will not be able to call a non-implemented method on any of the implementations

In Conclusion

It is harmful to depend on classes that have been forced to implement interfaces that they do not fully use. Interfaces should be created with a common purpose just like the Single Responsibility Principle

Violating this principle will make the code fragile. Smaller interfaces are easier to implement.

Originally published at https://nanosoft.co.za/blog/post/solid-isp

--

--