Tuesday, March 10, 2009

Updates to Lecture 7 examples

There were a few points that I missed during last night's lecture:

1. Every method has an implicit argument called this . This is the argument on which the method "works" and corresponds to the argument on which we are using the structure strategy. Recall how I wrote

(define (foo this)
(cond
[(empty? this) ...]
...))

Your purpose statement will almost always contain the word "this". That's a clue!

2. When you reference a field foo of an object, you should always say this.foo, not just foo. This is enforced in ProfessorJ/Beginner, but not in ProfessorJ/Intermediate. My examples violated this rule. So I should have said things like:

boolean test1 = check this.book1.listing() expect "Mitch: EOPL";

rather than

boolean test1 = check book1.listing() expect "Mitch: EOPL";


3. I was not happy with the method availableHelper :

boolean availableHelper (String title, int quantity) {
// is this book available in this quantity?
return ((this.ncopies >= quantity) && this.title.equals(title));
}

because (a) it violates the rule of 1-task/1-function and (b) it seems awfully artificial: it's not an obvious method for Book.

Here's a better solution: add to Book two methods

boolean titleEquals(String s) {
// does the title of this book equal s?
return this.title.equals(s);
}

boolean ncopiesGreaterThan(int n) {
// are at least n copies of this book on hand?
return this.ncopies >= n;
}

and in NeLOB redefine availableTitle to:


boolean availableTitle(String title, int n) {
// ... this.first ... this.rest.availableTitle(title, n) ...
if (this.first.titleEquals(title) && this.first.ncopiesGreaterThan(n))
{return true;}
else
{return this.rest.availableTitle(title,n);}
}


[Finger exercise: Modify the method so that if the title is found, but there aren't enough copies, the method returns false immediately, rather than recurring through the rest of the list.]

Anyhow, both these changes are in book2.java, now in the examples/Lecture 7 repository.

--Prof. Wand





No comments:

Post a Comment