Tuesday, October 21, 2008

Interface your world

The notion of interface in the Object Oriented Programming world has been always very confusing for developers. In this post I am reflecting about this very important notion and the role it plays in the Object Oriented philosophy. In a nutshell an interface is a contract that describes some behavior pieces and every developer wiling to use this interface is required to implement all the pieces. Here is what a contract looks like in the Java world. example1
 
public interface Vehicle {
    public void start();
    public void drive();
    public void park();
}
But, what do we need this interface for? Well, if you take sometime to think about it, you’ll find that it has many advantages. • It gives you control over your design because all the classes implementing a given interface are required to implement all the methods of your interface. • It makes your design flexible and loosely coupled. Below is an example of a method that can accept all the classes implementing List: example2:
 
List<String> list = new ArrayList<String>();
List<String> vector = new Vector<String>();
public void displayItems(List<String> list){
         for(String item:list){
            System.out.println(item);
        }
    }
We can call the method above like displayItems(list) or displayItems(vector). • It makes your code testable, through using mocks for example • It separates the concerns, because interface is used mainly to implement behavior and abstract class to provide properties. For example, we can have the Vehicle interface in example1 provide the behavior and have the abstract class below provide the properties: example3:
 
public abstract class VehicleDescription {
    public abstract String getColor();
    public abstract String getMake();
}
This class gets its behavior and proeprties from the interface and abstract classes described above.
 
public class Camry extends VehicleDescription implements Vehicle {
    private String color;
    private String make;
   
    public void start(){
        //implementation
    }

    public void drive(){
        //implementation
    }

    public void park(){
        //implementation
    }


    public String getColor() {
        return null;
    }

    public void setColor() {
        //implementation
    }

    public String getMake() {
        return null;
    }

    public void setMake() {
        //implementation
    }
}
Please feel free to speak your mind and add anything you see that i missed in this post to the comments.

No comments: