Wednesday, 25 July 2012

Interface segregation principle



Clients should not be forced to depend upon interfaces that they don't use.

Explanation:

When designing an application the abstraction of modules plays a vital role.We should take care that a client doesn't implement an interface , just because it has to implement.
Such an interface is named fat interface or polluted interface. Having an interface pollution is not a good solution and might induce inappropriate behavior in the system.
So instead of one large interface we should have many smaller interfaces with grouped behavior.


Example:

For example you have a service class for working with Category . And IManageCategory interface exposes
 three methods
  •  Add
  • Update
  •  and Delete.
 Because of some reasons of deployment and security we have to  divide this CategoryClass to  two 
different classes

  •  CreateCategory will implement the Add method and run in untrusted environments. 
  •  UpdateCategory, will implement the other two methods and will only run in secure verified and authenticated context. 
Now if I use the IManageCategory class I have to implement dummy void Update and Delete in my CreateCategory class and dummy void Add in my UpdateCategory class.
So, this has violated the design rule of Interface seggregation.


So, we have to divide the IManageCategory to two interfaces IAddCategory an IUpdateCategory.

Advantages of Using ISP:

  1. Better Understanadability
  2. Better Maintenability
  3. High Cohesion
  4. Low Coupling

Limitations

ISP like any other principle should be used intelligently when necessary otherwise it will result in a code containing lots of interfaces containing one method. So the decision should be taken intelligently.

No comments:

Post a Comment