31 October 2015

interface segregation principle

Interface segregation principle is one of the SOLID design principles. It stands for letter "I" in the "SOLID" acronym.

It states that Interface shouldn't be combined together which could lead to the fat interface, instead interfaces should be segregated or separated based on their real-world meaning closeness. If a behavior of a real-world object can exist as a separate entity in real world, consider defining an interface just alone for that set of behaviors.

Let’s consider an example to explain Interface Segregation Principle

Assume you are developing a vehicle which flies in the air, runs on water and run in the road. Then probably your interface looks like below:

interface IHybridVehicle
{
 void RunOnRoad();
 void Fly();
 Void RunOnWater();
}

Then any class implementing the IHybridVehicle will implement all the methods.

public class HyBridVehicle : IHyBridVehicle
{
  // Implementation for IHyBridVehicle methods
}

The problem with the above single fat interface approach:

When you have Hybrid Vehicle instance with you and just need the ability to run them on the road, even then you still end up having reference to an instance of IHyBridVehicle type. This happens because the current design is lacking an interface catering to each independent capability of the hybrid vehicle you are building.

The disadvantage of this fat interface design is that, when you want to remove /add/update methods/ behaviors, you have to consider the regression effort of the places wherever you got a reference to IHybridVehicle Interface. Definitely, such an effort will be huge because wherever you just need flying, traveling on road or sailing on water, you would have referred the single, big, fat interface IHybridVehicle.

Solving the problems having with fat Interface by using Interface Segregation Principle

Let’s separate the methods in IHybridVehicle to each interface whose implementation can have real-world independent existence and this time lets IHybridVehicle interface inherit from 3 interfaces.

interface IRoadVehicle
{
 void RunonRoad();
}

interface IWaterVehicle
{
 void FloatonWater();


interface ISkyVehicle
{
 void FlyinSky();
}
interface IHybridVehicle: IRoadVehicle, IWaterVehicle, ISkyVehicle
{
}

Advantage of applying Interface segregation principle:

  1. Now, if u want to just refer to just the ability of vehicle instance which runs on road, use it as IRoadVehicle, no need to refer to the big fat interface all over the places.
  2. And whenever you want IHybridVehicle as whole you can still do.

Hope you understood interface segregation principle. As always your comments are welcome!

No comments:

Post a Comment