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:
/** Composite Data Definition: * IntList := new Empty() + new Cons(int, IntList) */ abstract class IntList { ... /** Compute the sum of the elements in this. */ abstract int sum(); }
Next we need to generate examples showing the expected behavior of the method:
class TestIntList { /** Sample IntList values */ static final oneElt = new Cons(1, Empty.ONLY); static final twoElts = new Cons(5, oneElt); static final threeElts = new Cons(-10, twoElts); /** Test the sum() method, assuming that ans is * the correct answer for this.sum() */ void testSum(int ans) { int result = sum(); System.out.println("computed sum of " + this + " = " + sum()); if (result != ans) System.out.println("FAILURE: correct answer is " + ans); } /** Test driver method */ public void test() { Empty.ONLY.testSum(0); Cons.oneElt.testSum(1); Cons.twoElts.testSum(6); Cons.threeElts.testSum(-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 TestIntList.
Finger Exercise 1.7.4.1: Load your saved file IntList.java into DrJava Definitions pane and add the
definition of the sum method as described above. In the Interactions pane, run the tests specified in the test()
method of IntList. 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 that the Data Analysis and Design
step has already been done in IntList code. Save your revised
program in the file IntList.java.