Pages




Tuesday, August 9, 2011



Digg this

Interfaces: The First Step Toward Maintainable Software

Design Tools
Not too long ago I had a junior developer ask me, "What do you use interfaces for?"  The answer of course is that there are many reasons to use interfaces.  Interfaces specify contracts that classes and their methods must adhere to.  Put simply, an interface describes a family of objects that are interchangeable.

To demonstrate this concept, let's look at an interface commonly used in Java: java.util.Collection.  Lists, queues, sets, etc. in Java implement the Collection interface or some extension of that interface.  The interface Collection therefore describes the family
of objects that are instantiated from some class that implements either the Collection interface or an extension of that interface.

Take, for example, the following method:

public void printCollection(Collection<String> c) {
   java.util.Iterator iterator<String> = c.iterator();
   while (iterator.hasNext()) {
      System.out.println(iterator.next());
   }
}

Let's assume that the above method is part of a class Printer which has a default constructor.  Let's further assume that objects a, b, and c exist of class java.util.ArrayList, java.util.HashSet, and java.util.Stack, respectively.  The following code will then execute successfully.

Printer p = new Printer();
p.printCollection(a);
p.printCollection(b);
p.printCollection(c);

How do I know the above code will execute successfully?  Because java.util.ArrayList, java.util.HashSet, and java.util.Stack all implement the Collection interface.  So, even though the method printCollection required the type Collection as an argument, objects defined by of those three classes will work in it's place because they each implement Collection.  Therefore, their contract is defined by Collection and guaranteed to have the same method signatures as Collection.

The ability for objects a, b and c to change their form so that they can be used as objects of the type Collection is called polymorphism, which is a concept fundamental to object oriented programming.

How Is This Useful?
Interfaces allow us to build flexible software because we don't actually have to know the implementation of a class to accept a type as an argument.  And because specifying an argument creates a dependency, we can create dependencies on contracts (interfaces) instead of implementations (classes).  This allows any class that adheres to the contract defined by the interface to b interchanged with any other class adhering to that same interface.  And that is how loosely coupled software and more maintainable software begins.




No comments:

Post a Comment