SOLID Principles: Interface Segregation

Interface segregation is another technique that helps in keeping the system loosely coupled by dividing the functionality into small components.

The Interface Segregation Principle “I”

It states that no client should be forced to depend on methods it does not use. In other words, only relevant methods and functionalities should be exposed to clients and clients should have ability to pick and choose what’s relevant to them.

The problem with creating large Interfaces and hence heavy classes is that every client may not require all the functionality offered by the large Interface but they end up including things they don’t use. This leads to a very common issue in the Software Life-cycle where things break as a side-effect of some other change. Unexpected errors may occur for a client when there are changes in certain areas of the underlying application (which are not even being used by the client).

Interface Segregation can be considered an extension of Single Responsibility Principle which helps in segregating related but different functionalities.

Consider the example of a generalized E-Commerce platform which can be utilized for sale & delivery of physical goods and electronic subscription.

Classes which handle Delivery can be defined like this:

Figure 1

Some of OrderDelivery methods like assignPostalServiceProvider() may not be applicable for ElectronicDelivery. Clients that only require ElectronicDelivery will unnecessarily get the APIs specific to Physical Delivery.

class ElectronicDelivery implements OrderDelivery {

  @Override
  public void assignPostalServiceProvider(String provider) {
    //Do nothing
  }
}

Any changes related to Physical Delivery in the OrderDelivery interface, would require updates in the ElectronicDelivery concrete implementation too. It is useless but necessary change that can be avoided with proper segregation of Interfaces like:

Figure 2

The way classes are defined in Figure 2 is much cleaner and each class contains only relevant behavior.

Conclusion

When each class contains only relevant functionality, then client applications are never impacted by unused dependencies. Interface Segregation helps in reducing side-effect bugs during the maintenance of Application.