What Is a Contract?

 <  Day Day Up  >  

In the context of this article, 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 contact as "an agreement between two or more parties, especially one that is written and enforceable by law."

This is exactly what happens when a developer uses an API ”with the project manager or business owner representing the law. 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 coding practices.

The Term Contract

The term contract is widely used in many aspects of business, including software development. Do not confuse the concept here with other possible software design concepts called contracts.


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 code 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.

C#

For this chapter, I use C# as the .NET representative. However, these concepts apply to all .NET languages, such as Visual Basic .NET.


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 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 the class must provide a method called draw() , the class must provide its own implementation of the code. For example, a class called Circle and a class called 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. An abstract class hierarchy.

graphics/08fig03.gif

In this way, we have a Shape framework that is truly polymorphic. The Draw method can be invoked for every 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(); } 

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 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 in its attempt 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.

Circle

If Circle does indeed fail to implement a draw() method, Circle will be considered abstract. Thus, yet another subclass must inherit from Circle and implement a draw() method. This subclass would then become the concrete implementation of both Shape and Circle .


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 provide concrete methods as well.) 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.

Caution

Be aware that in the cases of Shape , Circle , and Rectangle , we are dealing with a strict inheritance relationship, as opposed to an interface, which we will discuss in the next section. Circle is a Shape, and Rectangle is a Shape . This is an important point because contracts are not meant to be used in cases of composition or has-a relationships.


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

Interfaces

Before defining an interface, it is important 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 C# bother to provide interfaces?

Interface Terms

The term interface used in earlier chapters is a term generic to OO programming, and refers to the public interface to a class. The term Java interface refers to a language construct that is specific to Java. It is important not to get the two terms confused . (Actually, interfaces are not specific to only Java; other OO languages use them as well.)


For one thing, C++ supports multiple inheritance, whereas Java and C# do not. Although Java and C# 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 C# cannot go this route. Although this explanation might specify the need for Java and C# interfaces, it does not really explain what an interface is. Let's explore what function an interface performs.

No Replacement for Multiple Inheritance

Because of these considerations, interfaces are often thought to be a workaround for the lack of multiple inheritance. This is not technically true. Interfaces are a separate design technique, and although they can be used to design applications that could be done with multiple inheritance, they do not replace the concept of multiple inheritance.


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. A UML diagram of a Java interface.

graphics/08fig04.gif

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. As a result, any class that implements an interface must provide the implementation for all methods. (In Java, a class inherits from an abstract class, whereas a class implements an interface.)

Implementation Versus Definition Inheritance

Sometimes inheritance is referred to as implementation inheritance , and interfaces are called definition inheritance .


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?

Compiling This Code

If you want to compile this Java code, make sure that you set classpath to the current directory:

 
 javac -classpath . Nameable.java javac -classpath . Mammal.java javac -classpath . Head.java javac -classpath . Dog.java 

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. A UML diagram of the sample code.

graphics/08fig05.gif

In a nutshell , Java and C# 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. 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, 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. 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.

Nameable Interface

An interface specifies certain behavior, but not the implementation. By implementing the Nameable interface, you are saying that you will provide nameable behavior by implementing methods called getName and setName . How you implement these methods is up to you. All you have to do is to provide the methods.


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 a good 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 problem 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.

 <  Day Day Up  >  


Object-Oriented Thought Process
Object-Oriented Thought Process, The (3rd Edition)
ISBN: 0672330164
EAN: 2147483647
Year: 2003
Pages: 164
Authors: Matt Weisfeld

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net