Friday, September 21, 2007

Programming to an Interface

This interesting post http://blog.sidu.in/2007/09/programming-to-interfaces-strikes-again.html inspired me to pen down my thoughts on this topic as well.

So here are my thoughts:-

1) What does it mean when you say "Program to an interface"? In order to answer this question lets take a look at the following snippet in Java.

First Snippet:-

public Animal {

public eat() {

// blah blah

}

}


public Horse extends Animal {

public eat() {

// blah blah

}

}

Second Snippet:-

public interface Animal {

void eat();

}


public class Horse implements Animal {

public void eat() {

//blah blah

}

}

Third Snippet:-

public interface Animal {

void eat();

}

public abstract class Mammal implements Animal {

public void eat() {

// some default implementation

}

}

In the above snippets Animal is a supertype and the way in which animals eat is different for eg:- a human being would chew and eat , a snake would swallow etc..... In this scenario you can achieve polymorphism via inheritance to solve this problem or an interface to decide on the implementation. The approach depends on the situation you are faced with. Inheritance promote code reuse when you have default implementations in a hierarchy however at the same time the subclasses are tightly coupled to the super class. Any change in the super class would propogate through the entire hierarchy which can become a maintainence nightmare if care is not taken.

On the other hand with interfaces you need to implement each method defined in all the classes that implement the interface. With interfaces you can have a class implementing one or more interfaces which provides flexibility. The interface approach also promotes the wrapper pattern.
Having said all this there is another approach you can take known as the skeletal implementation where you define the type using an interface and provide an abstract class that implements the interface with the default methods. This is very evident in the collection classes of the Java API.

So now we have three ways of solving the same problem..... What next? Finally in Java
When a class implements an interface, the interface serves as a type that can be used to refer
to instances of the class. A class that implements an interface should therefore say something
about what a client can do with instances of the class. It is inappropriate to define an interface
for any other purpose.

Conceptually speaking an interface is nothing but a supertype. The supertype could be a concrete class, an abstract class or the java construct "interface". Programming to an interface in Java does not mean having a Java interface for all classes unless the scenario demands it.

No comments: