Home > Articles > Software Development & Management > Object Technology

  • Print
  • + Share This
This chapter is from the book

What Is a Contract?

In the context of this chapter, we will consider a contract to be any mechanism that requires a developer to comply with the specifications of an Application Programming Interface (API). Often, an API is referred to as a framework. The online dictionary Dictionary.com (http://www.dictionary.com) defines a contract as an agreement between two or more parties for the doing or not doing of something specified—an agreement enforceable by law."

This is exactly what happens when a developer uses an API—with the project manager, business owner or industry standard providing the enforcement. When using contracts, the developer is required to comply with the rules defined in the framework. This includes issues like method names, number of parameters, and so on. In short, standards are created to facilitate good development practices.

Enforcement is vital because it is always possible for a developer to break a contract. Without enforcement, a rogue developer could decide to reinvent the wheel and write her own code rather than use the specification provided by the framework. There is little benefit to a standard if people routinely disregard or circumvent it. In Java and the .NET languages, the two ways to implement contracts are to use abstract classes and interfaces.

Abstract Classes

One way a contract is implemented is via an abstract class. An abstract class is a class that contains one or more methods that do not have any implementation provided. Suppose that you have an abstract class called Shape. It is abstract because you cannot instantiate it. If you ask someone to draw a shape, the first thing they will most likely ask you is "What kind of shape?" Thus, the concept of a shape is abstract. However, if someone asks you to draw a circle, this does not pose quite the same problem because a circle is a concrete concept. You know what a circle looks like. You also know how to draw other shapes, such as rectangles.

How does this apply to a contract? Let's assume that we want to create an application to draw shapes. Our goal is to draw every kind of shape represented in our current design, as well as ones that might be added later. There are two conditions we must adhere to.

First, we want all shapes to use the same syntax to draw themselves. For example, we want every shape implemented in our system to contain a method called draw(). Thus, seasoned developers implicitly know that to draw a shape you simply invoke the draw() method, regardless of what the shape happens to be. Theoretically, this reduces the amount of time spent fumbling through manuals and cuts down on syntax errors.

Second, remember that it is important that every class be responsible for its own actions. Thus, even though a class is required to provide a method called draw(), that class must provide its own implementation of the code. For example, the classes Circle and Rectangle both have a draw() method; however, the Circle class obviously has code to draw a circle, and as expected, the Rectangle class has code to draw a rectangle. When we ultimately create classes called Circle and Rectangle, which are subclasses of Shape, these classes must implement their own version of Draw (see Figure 8.3).

Figure 8.3

Figure 8.3 An abstract class hierarchy.

In this way, we have a Shape framework that is truly polymorphic. The Draw method can be invoked for every single shape in the system, and invoking each shape produces a different result. Invoking the Draw method on a Circle object draws a circle, and invoking the Draw method on a Rectangle object draws a rectangle. In essence, sending a message to an object evokes a different response, depending on the object. This is the essence of polymorphism.

circle.draw();       // draws a circle
rectangle.draw();   // draws a rectangle

Let's look at some code to illustrate how Rectangle and Circle conform to the Shape contract. Here is the code for the Shape class:

public abstract class Shape {

    public abstract void draw(); // no implementation

}

Note that the class does not provide any implementation for draw(); basically there is no code and this is what makes the method abstract (providing any code would make the method concrete). There are two reasons why there is no implementation. First, Shape does not know what to draw, so we could not implement the draw() method even if we wanted to.

Second, we want the subclasses to provide the implementation. Let's look at the Circle and Rectangle classes:

public class Circle extends Shape {

    public void Draw() {System.out.println ("Draw a Circle"};

}

public class Rectangle extends Shape {

    public void Draw() {System.out.println ("Draw a Rectangle"};

}

Note that both Circle and Rectangle extend (that is, inherit from) Shape. Also notice that they provide the actual implementation (in this case, the implementation is obviously trivial). Here is where the contract comes in. If Circle inherits from Shape and fails to provide a draw() method, Circle won't even compile. Thus, Circle would fail to satisfy the contract with Shape. A project manager can require that programmers creating shapes for the application must inherit from Shape. By doing this, all shapes in the application will have a draw() method that performs in an expected manner.

Although the concept of abstract classes revolves around abstract methods, there is nothing stopping Shape from actually providing some implementation. (Remember that the definition for an abstract class is that it contains one or more abstract methods—this implies that an abstract class can also provide concrete methods.) For example, although Circle and Rectangle implement the draw() method differently, they share the same mechanism for setting the color of the shape. So, the Shape class can have a color attribute and a method to set the color. This setColor() method is an actual concrete implementation, and would be inherited by both Circle and Rectangle. The only methods that a subclass must implement are the ones that the superclass declares as abstract. These abstract methods are the contract.

Some languages, such as C++, use only abstract classes to implement contracts; however. Java and .NET have another mechanism that implements a contract called an interface.

Interfaces

Before defining an interface, it is interesting to note that C++ does not have a construct called an interface. For C++, an abstract class provides the functionality of an interface. The obvious question is this: If an abstract class can provide the same functionality as an interface, why do Java and .NET bother to provide this construct called an interface?

For one thing, C++ supports multiple inheritance, whereas Java and .NET do not. Although Java and .NET classes can inherit from only one parent class, they can implement many interfaces. Using more than one abstract class constitutes multiple inheritance; thus Java and .NET cannot go this route. Although this explanation might specify the need for Java and .NET interfaces, it does not really explain what an interface is. Let's explore what function an interface performs.

As with abstract classes, interfaces are a powerful way to enforce contracts for a framework. Before we get into any conceptual definitions, it's helpful to see an actual interface UML diagram and the corresponding code. Consider an interface called Nameable, as shown in Figure 8.4.

Figure 8.4

Figure 8.4 A UML diagram of a Java interface.

Note that Nameable is identified in the UML diagram as an interface, which distinguishes it from a regular class (abstract or not). Also note that the interface contains two methods, getName() and setName(). Here is the corresponding code:

public interface Nameable {

    String getName();
    void setName (String aName);

}

In the code, notice that Nameable is not declared as a class, but as an interface. Because of this, both methods, getName() and setName(), are considered abstract and there is no implementation provided. An interface, unlike an abstract class, can provide no implementation at all. As a result, any class that implements an interface must provide the implementation for all methods. For example, in Java, a class inherits from an abstract class, whereas a class implements an interface.

Tying It All Together

If both abstract classes and interfaces provide abstract methods, what is the real difference between the two? As we saw before, an abstract class provides both abstract and concrete methods, whereas an interface provides only abstract methods. Why is there such a difference?

Assume that we want to design a class that represents a dog, with the intent of adding more mammals later. The logical move would be to create an abstract class called Mammal:

public abstract class Mammal {

    public void generateHeat() {System.out.println("Generate heat");}

    public abstract void makeNoise();

}

This class has a concrete method called generateHeat(), and an abstract method called makeNoise(). The method generateHeat() is concrete because all mammals generate heat. The method makeNoise() is abstract because each mammal will make noise differently.

Let's also create a class called Head that we will use in a composition relationship:

public class Head {

    String size;

    public String getSize() {

        return size;

    }

    public void setSize(String aSize) { size = aSize;}

}

Head has two methods: getSize() and setSize(). Although composition might not shed much light on the difference between abstract classes and interfaces, using composition in this example does illustrate how composition relates to abstract classes and interfaces in the overall design of an object-oriented system. I feel that this is important because the example is more complete. Remember that there are two ways to build object relationships: the is-a relationship, represented by inheritance, and the has-a relationship, represented by composition. The question is: where does the interface fit in?

To answer this question and tie everything together, let's create a class called Dog that is a subclass of Mammal, implements Nameable, and has a Head object (see Figure 8.5).

Figure 8.5

Figure 8.5 A UML diagram of the sample code.

In a nutshell, Java and .NET build objects in three ways: inheritance, interfaces, and composition. Note the dashed line in Figure 8.5 that represents the interface. This example illustrates when you should use each of these constructs. When do you choose an abstract class? When do you choose an interface? When do you choose composition? Let's explore further.

You should be familiar with the following concepts:

  • Dog is a Mammal, so the relationship is inheritance.
  • Dog implements Nameable, so the relationship is an interface.
  • Dog has a Head, so the relationship is composition.

The following code shows how you would incorporate an abstract class and an interface in the same class.

public class Dog extends Mammal implements Nameable {

    String name;

    Head head;

    public void makeNoise(){System.out.println("Bark");}

    public void setName (String aName) {name = aName;}
    public String getName () {return (name);}

}

After looking at the UML diagram, you might come up with an obvious question: Even though the dashed line from Dog to Nameable represents an interface, isn't it still inheritance? At first glance, the answer is not simple. Although interfaces are a special type of inheritance, it is important to know what special means. Understanding these special differences are key to a strong object-oriented design.

Although inheritance is a strict is-a relationship, an interface is not quite. For example:

  • A dog is a mammal.
  • A reptile is not a mammal

Thus, a Reptile class could not inherit from the Mammal class. However, an interface transcends the various classes. For example:

  • A dog is nameable.
  • A lizard is nameable.

The key here is that classes in a strict inheritance relationship must be related. For example, in this design, the Dog class is directly related to the Mammal class. A dog is a mammal. Dogs and lizards are not related at the mammal level because you can't say that a lizard is a mammal. However, interfaces can be used for classes that are not related. You can name a dog just as well as you can name a lizard. This is the key difference between using an abstract class and using an interface.

The abstract class represents some sort of implementation. In fact, we saw that Mammal provided a concrete method called generateHeat(). Even though we do not know what kind of mammal we have, we know that all mammals generate heat. However, an interface models only behavior. An interface never provides any type of implementation, only behavior. The interface specifies behavior that is the same across classes that conceivably have no connection. Not only are dogs nameable, but so are cars, planets, and so on.

The Compiler Proof

Can we prove or disprove that interfaces have a true is-a relationship? In the case of Java (and this can also be done in C# or VB), we can let the compiler tell us. Consider the following code:

Dog D = new Dog();
Head H = D;

When this code is run through the compiler, the following error is produced:

Test.java:6: Incompatible type for Identifier. Can't convert Dog to Head. Head H = D;

Obviously, a dog is not a head. Not only do we know this, but the compiler agrees. However, as expected, the following code works just fine:

Dog D = new Dog();
Mammal M = D;

This is a true inheritance relationship, and it is not surprising that the compiler parses this code cleanly because a dog is a mammal.

Now we can perform the true test of the interface. Is an interface an actual is-a relationship? The compiler thinks so:

Dog D = new Dog();
Nameable N = D;

This code works fine. So, we can safely say that a dog is a nameable entity. This is a simple but effective proof that both inheritance and interfaces constitute an is-a relationship.

Making a Contract

The simple rule for defining a contract is to provide an unimplemented method, via either an abstract class or an interface. Thus, when a subclass is designed with the intent of implementing the contract, it must provide the implementation for the unimplemented methods in the parent class or interface.

As stated earlier, one of the advantages of a contract is to standardize coding conventions. Let's explore this concept in greater detail by providing an example of what happens when coding standards are not used. In this case, there are three classes: Planet, Car, and Dog. Each class implements code to name the entity. However, because they are all implemented separately, each class has different syntax to retrieve the name. Consider the following code for the Planet class:

public class Dog extends Mammal implements Nameable {

    String name;

    Head head;

}
 public class Planet {

    String planetName;

    public void getplanetName() {return planetName;};

}

Likewise, the Car class might have code like this:

public class Car {

    String carName;

    public String getCarName() { return carName;};

}

And the Dog class might have code like this:

public class Dog {

    String dogName;

    public String getDogName() { return dogName;};

}

The obvious issue here is that anyone using these classes would have to look at the documentation (what a horrible thought!) to figure out how to retrieve the name in each of these cases. Even though looking at the documentation is not the worst fate in the world, it would be nice if all the classes used in a project (or company) would use the same naming convention—it would make life a bit easier. This is where the Nameable interface comes in.

The idea would be to make a contract for any type of class that needs to use a name. As users of various classes move from one class to the other, they would not have to figure out the current syntax for naming an object. The Planet class, the Car class, and the Dog class would all have the same naming syntax.

To implement this lofty goal, we can create an interface (we can use the Nameable interface that we used previously). The convention is that all classes must implement Nameable. In this way, the users only have to remember a single interface for all classes when it comes to naming conventions:

public interface Nameable {

    public String getName();
    public void setName(String aName);

}

The new classes, Planet, Car, and Dog, should look like this:

public class Planet implements Nameable {

    String planetName;

    public String getName() {return planetName;}
    public void setName(String myName) { planetName = myName;}

}

public class Car implements Nameable {

    String carName;

    public String getName() {return carName;}
    public void setName(String myName) { carName = myName;}

}

public class Dog implements Nameable {

    String dogName;

    public String getName() {return dogName;}
    public void setName(String myName) { dogName = myName;}

}

In this way, we have a standard interface, and we've used a contract to ensure that it is the case.

There is one little issue that you might have thought about. The idea of a contract is great as long as everyone plays by the rules, but what if some shady individual doesn't want to play by the rules (the rogue programmer)? The bottom line is that there is nothing to stop someone from breaking the standard contract; however, in some cases, doing so will get them in deep trouble.

On one level, a project manager can insist that everyone use the contract, just like team members must use the same variable naming conventions and configuration management system. If a team member fails to abide by the rules, he could be reprimanded, or even fired.

Enforcing rules is one way to ensure that contracts are followed, but there are instances in which breaking a contract will result in unusable code. Consider the Java interface Runnable. Java applets implement the Runnable interface because it requires that any class implementing Runnable must implement a run() method. This is important because the browser that calls the applet will call the run() method within Runnable. If the run() method does not exist, things will break.

System Plug-in-Points

Basically, contracts are "plug-in points" into your code. Anyplace where you want to make parts of a system abstract, you can use a contract. Instead of coupling to objects of specific classes, you can connect to any object that implements the contract. You need to be aware of where contracts are useful; however, you can overuse them. You want to identify common features such as the Nameable interface, as discussed in this chapter. However, be aware that there is a trade-off when using contracts. They might make code reuse more of a reality, but they make things somewhat more complex.

  • + Share This
  • 🔖 Save To Your Account