CS/SWE 332 In Class Exercise Number 25

Names:

Consider the example in Bloch's Item 50 (3rd Edition):

// Broken “immutable” time period class
public final class Period {               // Question 3
  private final Date start;
  private final Date end;

  /**
    * @param start the beginning of the period
    * @param end the end of the period; must not precede start
    * @throws IAE if start is after end
    * @throws NPE if start or end null
    */

  public Period (Date start, Date end) {
    if (start.compareTo(end) > 0) throw new IAE();
    this.start = start; this.end = end;  // Question 1
  }
  public Date start() { return start;}    // Question 2
  public Date end()   { return end;}      // Question 2
}
  1. Write code that shows the problem the line marked // Question 1.

  2. Write code that shows the problem the lines marked // Question 2.

  3. Suppose that the class declaration were:
    
    public class Period {               // Question 3
    

    Write code that shows the problem.

  4. Bloch fixes the constructor as follows:
    public Period (Date start, Date end) {
      this.start = new Date(start.getTime());  // Defensive copy
      this.end   = new Date(end.getTime());    // Defensive copy
    
      if (this.start.compareTo(end) > 0) throw new IAE();
    
    • Bloch states that clone() would be inappropriate for copying the dates. Write code that shows the problem.

    • Bloch defers the exception check until the end, which seems to violate normal practice. What's the problem with checking early?