In this five-part series, I’m covering each design principle laid out in SOLID. In this post, I am covering the Interface segregation principle.
The “I” in SOLID is a principle that is easy to skip over. Everyone will always remember the “S”, because it is first. The “L” is easy to remember because it is can be easily summed up as “use interfaces”. The “D” is easy to remember because it is dependency injection, which we all know.
That leaves us with the “O” and the “I”. The “O” is the Open / closed principle, which is the hardest one to link about to a service-oriented world. When we teach our Software Design and Engineering Clinics, we often refer to SOLID as SoLID because we don’t focus on the “O” much. But the “I” in SOLID is something we need to really focus on. It is super important but harder to understand.
The “I”, or Interface segregation principle (ISP) is about creating very specialized interfaces for the client / caller. It’s a good practice to create interfaces that are understandable from the perspective of the caller, but we often don’t want to create interfaces to be used by multiple callers.
The Interface segregation principle should encourage us to create different interfaces for to different clients. For example, we may have multiple clients if we are building an e-commerce application. We have a webstore for placing orders and an admin client for configuring stores and products. Keeping those two interfaces separate makes a lot of sense for three reasons:
- Coupling. If we make separate interfaces, we can decouple clients.
- Volatility. Those two interfaces can evolve separately over time.
- Understandability. A specific interface is more understandable than one that is more generally purposed.
How does this play out in code?
First, let’s look at something that poorly obeys the ISP.
Second, let’s look at something that better obeys the ISP.
The interface segregation principle is an easy principle to pass over, but it is essential to creating a loosely-coupled system that is pleasant to develop on two years later.