Programming Tutorials Browser Tutorials Articles Struts Tutorials Hibernate Tutorials

  Tutorial: Smarter Java development - JavaWorld August 1999

Smarter Java development - JavaWorld August 1999

Tutorial Details:

Smarter Java development
Smarter Java development
By: By Michael Cymerman
Use interfaces to effectively enforce development contracts while maintaining loose coupling of code
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


 

Read Tutorial at: Click here to view the tutorial

Rate Tutorial:
Smarter Java development - JavaWorld August 1999

View Tutorial:
Smarter Java development - JavaWorld August 1999

Related Tutorials:

3D graphics programming in Java, Part 3: OpenGL
3D graphics programming in Java, Part 3: OpenGL
 
Jini's relevance emerges, Part 1
Jini's relevance emerges, Part 1
 
J2SE 1.4 breathes new life into the CORBA community, Part 1
J2SE 1.4 breathes new life into the CORBA community, Part 1
 
Should you go with JMS?
Should you go with JMS?
 
Test email components in your software
Test email components in your software
 
Java Testing and Design
Java Testing and Java Test and Design is the companion to any book on Java software development practices, techniques, and testing. Software developers, QA analysts and IT managers working in large corporate IT groups, software development companies, and
 
Java Development on Eclipse, Part 1
Java Development on Eclipse, Part 1 Author\'s note: In part one of a two-part series of excerpts from Eclipse\'s Chapter 2, we\'ll get down to the business of developing Java using Eclipse. We\'re going to take a look at using Eclipse for Java developm
 
JDemo
JDemo is the Java demonstration framework. Its concept is similar to the one of JUnit. As supplement to test driven software development, JDemo provides a new approach of demo driven development: When developing software, you write short code snippets (
 
Integrate COM and Java components
Interoperability issues have long made integration of Microsoft® Component Object Model (COM) and Java™ components a daunting task. The Development Tool for Java-COM Bridge, available from IBM alphaWorks, simplifies the job and also provides an evoluti
 
Development Tool for Java-COM Bridge
What is Development Tool for Java-COM Bridge? Development Tool for Java-COM Bridge is a tool for developing and enabling tight communication between JavaTM- and COM-based applications. An application running on Microsoft Windows® systems is typically co
 
Leverage JNLP and SOAP for Java Thick-client Development
Leverage JNLP and SOAP for Java Thick-client Development The hype during the mid-to-late 1990's over Java's utility to run swarms of autonomous applets was greatly exaggerated. This early enthusiasm (and marketing) for Java as a language with which devel
 
Java Servlets: Design Issues
This article covers the principal concepts associated with servlets. This article examines some of the design issues, and offers some guidelines on the applicability of Java servlets for web based application development.
 
100 % java open-source cryptographic software libraries.
Cryptixtm is an international volunteer effort to produce robust, open-source cryptographic software libraries. Cryptix products are free, both for commercial and non-commercial use and are being used by developers all over the world. Development is ...
 
J2J - Java to JavaScript integration.
It is a development tool lets you to integrate Java classes and JavaScript within your HTML pages. The main idea behind this product is how to call methods of Java classes right from JavaScript functions.
 
J2ME Technology Turns 5!
In 2004 the Java 2 Platform, Micro Edition (J2ME) celebrated its fifth anniversary. This article presents where J2ME is today.
 
Five Reasons to Move to the J2SE 5 Platform
Five important reasons to move to the Java 2 Platform, Standard Edition (J2SE platform) 5.0, supported by data and references to prove that the 5.0 release will reduce development and runtime costs.
 
Struts and Tiles aid component-based development
In the Java world, Struts is one of the best-known and most talked about open source embodiments of MVC.
 
Running Wine on the Sun Java Desktop System, Release 2
A BigAdmin reader describes how to install and use Wine, an open source implementation of the Windows API, on the Sun Java Desktop System, Release 2.
 
Sun Studio 10 Software Just Released
This world-class development environment is now extended to the AMD64 architecture and delivers reliable, scalable, and high-performance applications for the Solaris 10 Operating System.
 
NetBeans IDE 4.1
Out-of-the-box support for J2EE 1.4 and Web Services. Check out what early access release 2 can do for you!
 
Site navigation
 

 

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2006. All rights reserved.