Pages

Wednesday, September 22, 2010

OOP SOLID Rules : Interface Segregation Principle (ISP)




Introduction:
Object Oriented Programming (OOP) has 5 basic rules which shortly named as SOLID:
S : Single Responsibility Principle
O : Open Closed Principle
L : Liskov Substitution Principle
I : Interface Segregation Principle
D : Dependency Inversion Principle
Interface Segregation Principle is explained with examples (in Java language) in this article.

Explanation:
Some interfaces are created with huge amount of functionalities. But when those interfaces are implemented by client implementor classes, not required functionalities are forced to be implemented, and so the code will have many dummy or empty implementations.

This situation can be prevented by segregating (i.e seperating) big interfaces into smaller ones. Only strictly related method definitions must be in the same interface. Different types of functionalities must be placed in different interfaces.

Examples:
Below is a wrong design that's not using Interface Segregation Principle. Implementor classes have to implement unnecessary methods.

public interface Animal {
    void fly();
    void run();
    void bark();
}
public class Bird implements Animal {
    public void bark() { /* do nothing */ }
    public void run() {
        // write code about running of the bird
    }
    public void fly() {
        // write code about flying of the bird
    }
}
public class Cat implements Animal {
    public void fly() { throw new Exception("Undefined cat property"); }
    public void bark() { throw new Exception("Undefined cat property"); }
    public void run() {
        // write code about running of the cat
    }
}
public class Dog implements Animal {
    public void fly() { }
    public void bark() {  
        // write code about barking of the dog
    }
    public void run() {
        // write code about running of the dog
    }
}

And below is the implementation which uses ISP:

public interface Flyable {
    void fly();
}
public interface Runnable {
    void run();
}
public interface Barkable {
    void bark();
}
public class Bird implements Flyable, Runnable {
    public void run() {
        // write code about running of the bird
    }
    public void fly() {
        // write code about flying of the bird
    } 
}
public class Cat implements Runnable{
    public void run() {
        // write code about running of the cat
    }
}
public class Dog implements Runnable, Barkable {
    public void bark() {  
        // write code about barking of the dog
    }
    public void run() {
        // write code about running of the dog
    }
}

Interface Segregation Principle is one of the key points in OOP. By following this principle, growing interfaces will no longer be a problem.

1 comment:

  1. Bad example because I hate animal example. But great post. Thanks..

    ReplyDelete