SWE 619 In Class Exercise Number 12A


Consider the following (bad) Java, implementing the "C style" enum pattern:
public class Coins {
   public static final int PENNY = 1;
   public static final int NICKEL = 5;
   public static final int DIME = 10;
   public static final int QUARTER = 25;
}
  1. Give example code that illustrates a type safety problem with Coins. Work through a range of expressions from "probably ok" to "clearly wrong".

  2. What code would you need to turn a nickel into a string? Explain how this could go wrong at runtime.

  3. What code would you need to iterate through the coins?

  4. Write a decent Java Enum for coins.

  5. Turn a nickle into a string.

  6. Iterate though the coins.

Consider Bloch's example:
// Abuse of ordinal to derive an associated value – DON’T DO THIS
public enum Ensemble {
   SOLO,   DUET,   TRIO,  QUARTET, QUINTET, 
   SEXTET, SEPTET, OCTET, NONET,   DECTET;

   public int numberOfMusicians() { return ordinal() + 1; }
}
Explain why it's wrong, fix it, and add another enum with an overlapping number of musicians.