Smarter Java development

Use interfaces to effectively enforce development contracts while maintaining loose coupling of code

A quick and simple scheme to speed the development of large-scale Java applications involves the use of interfaces. Java interfaces are a blueprint for the functionality contained in an associated object.

By incorporating interfaces into your next project, you will noticebenefits throughout the lifecycle of your development effort. The technique of coding to interfaces rather than objects will improve the efficiency of the development team by:

  • Allowing the development team to quickly establish the interactions among the necessary objects, without forcing the early definition of the supporting objects
  • Enabling developers to concentrate on their development tasks with the knowledge that integration has already been taken into account
  • Providing flexibility so that new implementations of the interfaces can be added into the existing system without major code modification
  • Enforcing the contracts agreed upon by members of the development team to ensure that all objects are interacting as designed

An overview

Because object-oriented development efforts involve the interactions of objects, it is essential to develop and enforce strong contracts between those objects. The technique of coding to interfaces involves using interfaces, rather than objects, as the primary method of communication.

This article will introduce the user to the concept of coding to interfaces through a simple example. A detailed example will follow, helping demonstrate the value of this scheme in a larger system requiring multiple developers. Before we get to the sample code, however, let's look at the benefits of coding to interfaces.

Why code to interfaces?

The Java interface is a development contract. It ensures that a particular object satisfies a given set of methods. Interfaces are used throughout the Java API to specify the necessary functionality for object interaction. Examples of interface use are callback mechanisms (Event Listeners), patterns (Observer), and specifications (Runnable, Serializable).

Coding to interfaces is a technique by which developers can expose certain methods of an object to other objects in the system. The developers who receive implementations of these interfaces have the ability to code to the interface in place of coding to the object itself. In other words, the developers would write code that did not interact directly with an object as such, but rather with the implementation of that object's interface.

Another reason to code to interfaces rather than to objects is that it provides higher efficiency in the various phases of a system's lifecycle:

  • Design: the methods of an object can be quickly specified and published to all affected developers
  • Development: the Java compiler guarantees that all methods of the interface are implemented with the correct signature and that all changes to the interface are immediately visible to other developers
  • Integration: there is the ability to quickly connect classes or subsystems together, due to their well-established interfaces
  • Testing: interfaces help isolate bugs because they limit the scope of a possible logic error to a given subset of methods

There is some overhead associated with this development technique, due to the required code infrastructure. This infrastructure includes both interfaces for the interactions between objects and invocation code to create implementations of interfaces. This overhead is insignificant when compared to the ease and benefit of using interfaces as described.

Basic example

To further explain the concept of coding to interfaces, I have created a simple example. While this example is clearly trivial, it demonstrates some of the benefits mentioned above.

Consider the simple example of a class Car that implements interface Vehicle. Interface Vehicle has a single method called start(). Class Car will implement the interface by providing a start() method. Other functionality in the Car class has been left out for the sake of clarity.

interface Vehicle {
        // All  vehicle implementations must implement the start method
   public void start();
}
class Car implements Vehicle{
        //  Required to implement Vehicle
   public void start(){ ... }
}

Having laid the foundations of the Car object, we can create another object called Valet. It is the Valet's job to start the Car and bring it to the restaurant patron. The Valet object can be written without interfaces, as follows:

class Valet {
   public Car getCar( Car c){ ... }
}

The Valet object has a method called getCar that returns a Car object. This code example satisfies the functional requirements of the system, but it forever links the Valet object with that of the Car. In this situation, the two objects are said to be tightly coupled. The Valet object requires knowledge of the Car object and has access to all public methods and variables contained within that object. It is best to avoid such tight coupling of code because it increases dependencies and reduces flexibility.

To code the Valet object using interfaces, the following implementation could be used:

class Valet{
   public Vehicle getVehicle( Vehicle c) {  ...  }
}

While the code changes are fairly minor -- changing the references from Car to Vehicle -- the effects on the development cycle are considerable. Using the second implementation, the Valet has knowledge only of the methods and variables defined in the Vehicle interface. Any other public methods and data contained in the specific implementation of the Vehicle interface are hidden from the user of the Vehicle object.

This simple code change has ensured the proper concealment of information and implementation from other objects, and has therefore eliminated the possibility that developers will use undesirable methods.

Creating the interface object

The last issue to discuss with respect to this development technique is the creation of the interface objects. While it is possible to create a new instance of a class using the new operator, it is not possible to directly create an instance of an interface. In order to create an interface implementation, you must instantiate the object and cast it to the desired interface. Therefore, the developer who owns the object code can be responsible for both creating the instance of the object and performing the casting.

This creation process can be achieved using a Factory pattern in which an external object calls a static createXYZ() method on a Factory and returns an interface. It can also be achieved if a developer calls a method on another object and passes it an interface instead of the actual class. This would be analogous to passing an Enumeration interface instead of a Vector or Hashtable.

Detailed example

In order to demonstrate the use of this scheme on a larger project, I have created the example of a meeting scheduler. This scheduler has three major components: the resources (conference room and meeting attendee), the occurrence (the meeting itself) and the scheduler (the one who maintains the resource calendar).

Let's assume these three components were to be developed by three different developers. The goal of each developer should be to establish the usage of his or her component and publish it to the other developers on the project.

Consider the example of a Person. A Person may implement numerous methods but will implement the Resource interface for this application. I have created the Resource interface with all the necessary accessor methods for all resources used in this example (shown below):

public interface Resource {
  public String getID();
  public String getName(); 
  
  public void addOccurrence( Occurrence o);
}

At this point, the developer of the Person functionality has published the interface by which all users can access the information stored in the Person object. Coding to the interface helps ensure that no developers are using the Person object in an incorrect manner. The developer of the Scheduler object can now use the methods contained in the Resource interface to access the information and functionality necessary to create and maintain the schedule of the Person object.

The Occurrence interface contains methods necessary for the scheduling of an Occurrence. This can be a conference, travel plan, or any other scheduling event. The Occurrence interface is shown below:

public interface Occurrence {
   
    public void setEndDatetime(Date d);
    public Date getEndDatetime();  
    public void setStartDatetime(Date d);
    public Date getStartDatetime();
    public void setDescription(String description);
    public String getDescription();
    
    public void addResource(Resource r);
    public Resource[] getResources();
    public boolean occursOn( Date d);
}

The Scheduler code uses the Resource interface and the Occurrence interface to maintain the schedule of a resource. Notice that the Scheduler does not have any knowledge of the entity for which it is maintaining the schedule:

public class Scheduler implements Schedule{
    Vector schedule = null;
    public Scheduler(){
       schedule = new Vector();
    }
    
public void addOccurrence(Occurrence o){
       schedule.addElement(o);
    }
    
        public void removeOccurrence(Occurrence o){
       schedule.removeElement(o);
    }
    
        public Occurrence getOccurrence(Date d)    {
       Enumeration scheduleElements = schedule.elements();
       
       Occurrence o = null;
       
       while ( scheduleElements.hasMoreElements() )  {
          o = (Occurrence) scheduleElements.nextElement();
        // For this simple example, the occurrence matches if 
        // the datetime isthe meeting start  time.  This logic
        // can be made more complex as required.
          if ( o.getStartDatetime() == d) {
             break;
          }
       }
       
       return o;
    }
}

This example shows the power of interfaces in the development phases of a system. Each of the subsystems has knowledge only of the interface through which it must communicate -- no knowledge of the implementation is required. If each of the building blocks in the above example were to be further developed by teams of developers, their efforts would be simplified due to the enforcement of these interface contracts.

Final thoughts on interfaces

This article has demonstrated some of the benefits of coding to interfaces. This technique enables greater efficiency throughout each phase of the development lifecycle.

During the design phases of the project, interfaces allow the quick establishment of the desired interactions among objects. The implementation objects associated with a given interface can be defined after the methods and requirements for that interface are specified. The more quickly the interaction is established, the more quickly the design phase can progress into development.

Interfaces give developers the ability to expose and limit certain methods and information to the users of their objects without changing the permissions and internal structure of the object itself. The use of interfaces can help eliminate the pesky bugs that appear when code developed by multiple development teams is integrated.

Contract enforcement is provided by the interface. Because the interface is generally agreed upon during the design phase of the project, the developers have the ability to concentrate on their individual modules without having to worry about the modules of their colleagues. Integrating these subsystems is made more efficient by the fact that the contracts have already been enforced throughout the development phase.

For testing purposes, a simple driver object can be created to implement the agreed-upon interfaces. Using this object, developers can continue their work with the knowledge that they are using the proper methods to access the object. When the objects are deployed in a test environment, the driver classes are replaced by the true classes, allowing the object to be tested without code or property changes.

This scheme provides the capability for easy expansion of this system; in our example, we could expand the code to include more forms of resources, such as meeting rooms and audio/video equipment. Any additional implementation of the Resource interface will fit into the established mechanism without modifying the existing code. Large-scale projects using this scheme could be designed and implemented in such a way that additional functionality can be added without major modification to the infrastructure. As an example, the ConferenceRoom object was created. This object implements the Resource interface and can interact with the Schedule and Occurrence implementers without changing the infrastructure.

Another benefit is the centralized location of the code. If new methods are to be added to the Resource interface, all implementations of this interface will be identified as requiring change. This will reduce the investigation required to determine the possible impact of changes to the interface.

In addition to the development benefits, the technique presented in this article provides project management with the assurance that interobject or intersystem communication patterns have been established and enforced throughout the development cycle. This reduces the risk of failures during the integration and testing phases of the project.

The only drawbacks to this scheme are the fact that there is some overhead associated with the creation and casting of objects, and the fact that more code is required to first specify the interface and then code the class that implements the interface. These two drawbacks seem insignificant, though, compared to the vast number of benefits. Coding to interfaces can help developers and managers alike. This scheme is a valuable tool that can be used in the development of Java-based systems.

Michael Cymerman is a senior consultant at Divya Incorporated (www.divya.com), a consulting firm specializing in Java/Internet software solutions. Michael provides Java/Internet based architecture, design, and development solutions to Fortune 500 companies.

Learn more about this topic

Join the discussion
Be the first to comment on this article. Our Commenting Policies