Friday, 17 February 2017

Interface-segregation principle


What is the point in selling a horse saddle for one who does not own a horse?

The interface segregation principle (ISP) states that no client should be forced to depend on methods it does not use. ISP splits interfaces that are very large into smaller and more specific ones so that clients will only have to know about the methods that are of interest to them.

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



ISP is intended to keep a system decoupled and thus easier to refactor, change, and redeploy.

When we design an application we should take care how we are going to make abstract a module which contains several submodules. Considering the module implemented by a class, we can have an abstraction of the system done in an interface. But if we want to extend our application adding another module that contains only some of the sub-modules of the original system, we are forced to implement the full interface and to write some dummy methods. Such an interface is named fat interface or polluted interface. Having interface pollution is not a good solution and might induce inappropriate behavior in the system.



//interface segregation principle - bad example
interface IWorker {
    
     public void work();
     public void eat();
}

class Worker implements IWorker {
     public void work() {
           // ....working
     }
     public void eat() {
           // ...... eating in lunch break
     }
}

class Robot implements IWorker {
     public void work() {
           //.... working much more
     }

     /** Dummy implementation while robot will not eat lunch.*/
     public void eat() {
           //.... eating in lunch break
     }
}

class Manager {
     IWorker worker;

     public void setWorker(IWorker w) {
           worker=w;
     }

     public void manage() {
           worker.work();
     }
}

If the design is already done fat interfaces can be segregated using the Adapter pattern.



// interface segregation principle - good example
interface IWorker extends IFeedable, IWorkable {
}

interface IWorkable {
     public void work();
}

interface IFeedable{
     public void eat();
}

class Worker implements IWorkable, IFeedable {
     public void work() {
           // ....working
     }

     public void eat() {
           //.... eating in lunch break
     }
}

class Robot implements IWorkable {
     public void work() {
           // ....working
     }
}

class Manager {
     IWorker worker;

     public void setWorker(IWorker w) {
           worker=w;
     }

     public void manage() {
           worker.work();
     }
}

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...