Effective Interface with ISP

Explore how ISP advocates for keeping interfaces focused on single responsibilities, minimizing the number of methods to ensure clarity and cohesion in code design.

Keeping interfaces effective and focused

In this lesson, we will look at a principle that helps us write effective interfaces. It is known as ISP. ISP advises us to keep our interfaces small and dedicated to achieving a single responsibility. By small interfaces, we mean having as few methods as possible on any single interface. These methods should all relate to some common theme. We can see that this principle is really just SRP in another form. We are saying that an effective interface should describe a single responsibility. It should cover one abstraction, not several. The methods on the interface should strongly relate to each other and also to that single abstraction.

ISP in action

If we need more abstractions, then we use more interfaces. We keep each abstraction in its own separate interface, which is where the term interface segregation comes from —we keep different abstractions apart. The related code smell to this is a large interface that covers several different topics in one. We could imagine an interface having hundreds of methods in little groups—some relating to file management, some about editing documents, and some about printing documents. Such interfaces quickly became difficult to work with. ISP suggests that we improve this by splitting the interface into several smaller ones. This split would preserve the groups of methods—so, you might see interfaces for file management, editing, and printing, with relevant methods under each. We have made our code simpler to understand by splitting apart these separate abstractions.

Interface design with ISP

The most noticeable use of ISP is in the Shape interface, as illustrated here:

Get hands-on with 1200+ tech skills courses.