4.7  Example: Determine which of two books was written by an earlier author

1. Data Analysis and Problem Analysis

The problem deals with two books - this book and that book.

2. Purpose and Contract/Header:

  // determine whether this book was written by an earlier author
  // than that book
  boolean earlier(Book that) { ... }

3. Examples:

  Author mf = new Author("Matthias", 1900);
  Author pc = new Author("Pat Conroy", 1940);
  Book b1 = new Book("HtDP", mf, 60, 2001);
  Book b2 = new Book("Beach Music", pc, 20, 1996);
  ...
  b1.earlier(b2)  -- expected: true
  b2.earlier(b1)  -- expected: false

4. Template:

The template includes the field selectors for both this book and for that book, as well as the field selectors for the respective authors.

  boolean earlier(Book that) { ... }
    ... this.title ...            ... that.title ...
    ... this.author ...           ... that.author ...
        ... this.author.name ...      ... that.author.name ...
        ... this.author.dob ...       ... that.author.dob ...
    ... this.price ...            ... that.price ...
    ... this.year ...             ... that.year ... }

5. Program:

  // determine whether this book was written by an earlier author
  // than that book
  boolean earlier(Book that) { 
    return this.author.dob < that.author.dob;  } 

6. Tests:

  b1.earlier(b2) == true
  b2.earlier(b1) == false