Interface Segregation Principle- Program to an interface

Robert Martin has a very good explanation of Interface segregation principle (ISP), in his book “UML for Java Programmers”. Based on that, I don’t think ISP is about an interface being “focused” on one logical, coherent group of things. Because, that goes without saying; or, at least it should go without saying. Each class, interface or abstract class should be designed that way.

So, what is ISP? Let me explain it with an example. Say, you have a class A and a class B, which is the client of class A. Suppose, class A has ten methods, of which only two are used by B. Now, does B need to know about all ten methods of A? Probably not – the principle of Information hiding. The more you expose, the more you create the chance for coupling. For that reason, you may insert an interface, call it C, between the two classes (segregation). That interface will only declare the two methods that are used by B, and B will depend on that Interface, instead of directly on A.

So now,

class A {
  method1()
  method2()
  // more methods
  method10()
}

class B {
   A a = new A()
}

will become

interface C {
  method1()
  method2()
}

class A implements C{
  method1()
  method2()
  // more methods
  method10()
}

class B {
  C c = new A()      
}   

This, prevents B from knowing more than it should.

Leave a Comment