We are now ready to define a simple program to sum the integers in a lists. 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 and header for sum in the abstract class IntList:
// IntList := Empty() + Cons(Object, 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(Object, IntList) abstract class IntList { ... abstract int sum(); // returns the sum of the numbers in this void test(int ans) { // assumes that ans is the correct answer for this.sum() // prints this and the this.sum(); // reports failure if result does not match ans int result = sum(); System.out.println("computed sum of " + this + " = " + sum()); if (result != ans) System.out.println("FAILURE: correct answer is " + ans); } public static void main(String[] args) { // test method Empty.only.test(0); Cons.oneElt.test(1); Cons.twoElts.test(6); Cons.threeElts.test(-4); } }
As the fourth step, we select a template for writing the sum method:
class Empty { ... 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 main method of IntList.
Finger exercise: Load the IntList2 sample program into the
DrJava Definitions window. In the Interactions window,
run the tests specified in IntList.main. Using the design
recipe, add a definition of a method prod to compute the product
of a list of numbers and test it. Note that the Data Analysis
and Design step has aleady been done in IntList code.