SOLID – Interface Segregation Principle

Definition :

Clients should not be forced to depend upon interfaces that they do not use. Or as Uncle Bob says: Make fine grained interfaces that are client specific.

dggn8fwf_33cq6mtncq_b

The idea in this picture that we have a very small dependency which is the USB cable in the upper left but instead of being able to plug that into a USB port in a computer or something, we are forced to use that device here in the right which contains buttons , switches and lights and a lot of things that we don’t need.

When we have non-cohesive interfaces, the ISP guides us to create multiple, smaller, cohesive interfaces. The original class implements each such interface. Client code can then refer to the class using the smaller interface without knowing that other members exist.

Example:-

We have a fat Interface called IBird that contains these four methods or behaviors ( Walk , Eat , Sleep, Fly )

3-6-2013 2-19-02 PM

Now, if a Bird class (ex. Penguin) implements this interface we will be breaking ISP principle as we will force the Penguin class to implement the Fly method which is unnecessary for it because penguins doesn’t fly.

To Solve this problem we have to split that interface into two small interfaces IBrid and IFlyingBird which will inherits from the IBird Interface .

3-6-2013 2-20-34 PM

Now if there is a bird that can’t fly (ex. Penguin), it would implement the IBird interface. And if there is a bird that can fly (ex. Dove), it would implement the IFlyingBird  interface.

Smaller interfaces are easier to implement, improving flexibility and the possibility of reuse. As fewer classes share interfaces, the number of changes that are required in response to an interface modification is lowered. This increases robustness of your code.

Related Posts:
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s