5.4  Example: Making a list of expensive books

1. Data Analysis and Problem Analysis

We need is the list of books and the title of the book to look for.

2. Purpose and Contract/Header:

  // PURPOSE AND CONTRACT:
  // produce a list of all books in this list that cost more than 
  // the given price
  abstract boolean costMoreThan(int amount);

We develop the methods in the two classes concurrently, starting with examples.

3. Examples:

We use the same data as in the previous two problems.

  mtlob.costMoreThan(15)  -- expected: mtlob
  lob1.costMoreThan(15)   -- expected: lob1
  lob2.costMoreThan(25)   -- expected: lob1
  lob3.costMoreThan(18)   -- expected: lob2
  lob2.costMoreThan(70)   -- expected: mtlob

4. Template:

There is a separate template for each of the two subclasses.

  /* TEMPLATE for the MtLoB class:
  boolean costMoreThan(int amount) {
    ...  }  */

 /* TEMPLATE for the ConsLoB class:
  boolean costMoreThan(int amount) {
     ... this.fst ...
        ... this.fst.title ...
        ... this.fst.author ...
        ... this.fst.price ...

            if (this.fst.price < amount) ...
            else ...

        ... this.fst.year ...
    ... this.rst.find(title) ... }  */

5. Program:

Again, we have two different methods, one for each class.

  // PROGRAM for the class MtLoB: 
  ALoB costMoreThan(int amount){ return this; }

  // PROGRAM for the class ConsLoB: 
  ALoB costMoreThan(int amount){ 
    if (this.fst.price < amount)
      return this.rst.costMoreThan(amount); 
    else
      return new ConsLoB(this.fst, this.rst.costMoreThan(amount));
  }
 

6. Tests:

We can no longer test two lists directly for equality. The Test Case tool understands how to compare two lists, even if they have been built at different times.

Note: This is a difficult topic, but students need to understand it to become good programmers. By constructing tests carefully from the beginning, students become aware of the difficulties and start asking the questions that expose the different kinds of equality.