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.
We'll cover the following
Keeping interfaces effective and focused
In this lesson, we’ll look at a principle that helps us write effective interfaces, known as ISP (Interface Segregation Principle). It 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’re 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, we 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 1400+ tech skills courses.