We are now ready to define a simple program to sum the integers in a list. We will add a definition of the method
int sum();to each class in our composite class hierarchy for IntList. Let's begin by writing the contract, header, and purpose for sum in the abstract class IntList:
/** IntList := Empty() + Cons(int, IntList) */
abstract class IntList {
...
abstract int sum();
// returns the sum of the numbers in this
}
Next we need to generate examples showing the expected behavior of the method:
/** IntList := Empty() + Cons(int, IntList) */
abstract class IntList {
...
/** returns the sum of the numbers in this */
abstract int sum();
/** prints a failure message if this.sum() != ans */
void check(int ans) {
int result = sum();
System.out.println("computed sum of " + this + " = " + result);
if (result != ans)
System.out.println("FAILURE: correct answer is " + ans);
}
/** tests sum() by calling check on a variety of IntList values */
public static void test() {
Empty.only.check(0);
Cons.oneElt.check(1);
Cons.twoElts.check(6);
Cons.threeElts.check(-4);
}
}
As the fourth step, we select a template for writing the sum method:
class Empty extends IntList {
...
int sum() { ... }
}
class Cons extends IntList {
int first;
IntList rest;
...
int sum() { ... first ... rest ... rest.sum() ... ; }
}
Finally, we complete the coding process by filling in the bodies of the methods in the template:
class Empty {
...
int sum() { return 0; }
}
class Cons extends IntList {
int first;
IntList rest;
...
int sum() { return first + rest.sum(); }
}
To finish the design recipe, we test our code using the examples in the test method of IntList.
Finger Exercise: Load your saved file IntList.java into
DrJava Definitions window and add the definition of the sum
method as described above.
In the Interactions window,
run the tests specified in the method IntList.test(). Using the same
design recipe, add a definition of a method prod to compute the product
of a list of numbers and test it. (Note: the product of an empty list is 1.)
Note that the Data Analysis
and Design step has already been done in IntList code.
Save your revised program in the file IntList.java.