SWE 619 In Class Exercise Number 7B


// Chooser - a class badly in need of generics!
// Bloch 3rd edition, Chapter 5, Item 28:  Prefer lists to arrays

public class Chooser {
   private final Object[] choiceArray;

   public Chooser (Collection choices) {
      choiceArray = choices.toArray();
   }

   public Object choose() { 
      Random rnd = ThreadLocalRandom.current();
      return choiceArray [rnd.nextInt(choiceArray.length)];
   }
}
Note: Many of the ideas from 619 can be applied to this simple example. In this in-class, we'll just do a few.

Offline assignment: Adopt Bloch's advice about arrays and lists to get a typesafe Chooser class. Note that you can check your work against Bloch's solution.

Write contracts (that Liskov would like - and you would like!) for the constructor and choose method. Note: You will need to change the implementation. Be very careful with the contract for choose(). There are many ways to get this contract wrong, but you have enough training to get it right. In particular, recall that the only variables "in scope" for a method contract are a) the inputs to that method, b) the outputs from that method, and c) the (abstract) state of the object.

What would be a good rep-invariant for this class?

Suppose we decided that chooser objects shouldn't be empty? (See homework) Is that client visible? How would we document that? How would the rep-invariant change? How would the contracts change? How would the implementation change?

Suppose we decided that chooser objects shouldn't contain null references. Is that client visible? How would we document that? How would the rep-invariant change? How would the contracts change? How would the implementation change?