SOLID Principles : Part 4 of 5, Interface Segregation Principle

Before we talk about the Integration Segregation Principle lets first think about what an interface is. Lets take a modern TV. The interface of the TV is a power button, volume buttons, and some inputs for HDMI and outputs for audio. The interface is how a user will interact with the TV. Pressing the power button will turn the TV on or off.

We break the Interface Segregation Principle if we add something to the interface, that doesn’t do anything to change how the TV functions. What if all the electronics in our house were controlled by this TV interface? We control our house Roomba through the interface of the TV, turn on our playstation, set our blender speed, I think you are starting to get the point.

Interface Segregation Principle states that clients should not be forced to depend on methods they do not use. Much like we shouldn’t submit our TV users to buttons they will not use for the TV.

For a more practical example lets take a look at an example of how we might build a fantasy football website. The interface below is how a team owner might interact with their roster.

Here we have some basic functionality for an owner interacting with their roster. Through this RosterInteraction interface they can add a player, drop a player, find out their teams projected points for the week, and finding out more about injuries to the players.

Here is a class inheriting from this interface Roster Interaction called Roster Transaction.

Notice the last two methods ProjectedPoints and Injuries, we have to implement all the methods of the interface we are inheriting from. In this case these methods are void so we have nothing to implement, but if those methods expected a string, we have to return an empty string. We can see that is a code smell. We are defining functions but not implementing them.

More specifically though this is a code smell that is common when we are breaking ISP. When we have a class that inherits from an interface and is not implementing all the methods in a meaningful way, we are breaking the Integration Segregation Principle.

What we would do then to adhere to ISP is to split our interface into two. We would have a Roster Transaction interface and another called Roster Research.

Sweet not only are we following ISP, we are adhering to the Single Responsibility Principle as well. A Roster’s transactions and research are only responsible for one thing. Our resulting classes that inherit from these interface will look like this.

Nice we have our interfaces segregated out to where they belong. Tune in next time where we will be wrapping up the SOLID series by talking about Dependency Inversion Principle.