samples/cloneproblem/src/org/apidesign/cloneproblem/Interval.java
author Jaroslav Tulach <jtulach@netbeans.org>
Tue, 01 Mar 2011 21:28:39 +0100
changeset 368 e1089d423881
child 369 5171d544edeb
permissions -rw-r--r--
Demonstrating the 'clone' problem
     1 package org.apidesign.cloneproblem;
     2 
     3 import java.util.Date;
     4 
     5 // BEGIN: interval.api
     6 /** Quiz: Anyone can come up with a JUnit test to generate
     7  * {@link NullPointerException} directly from the code of 
     8  * the <code>Interval</code> class?
     9  *
    10  * @author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
    11  */
    12 public final class Interval {
    13     private final Date from, to;
    14     
    15     /** Constructs interval between two dates.
    16      * 
    17      * @param from the 'sooner' date
    18      * @param to the 'later' date
    19      * @throws IllegalArgumentException if <code>from</code> is not less then <code>to</code>
    20      */
    21     public Interval(Date from, Date to) {
    22         if (from == null) {
    23             throw new IllegalArgumentException("'from' cannot be null!");
    24         }
    25         if (to == null) {
    26             throw new IllegalArgumentException("'to' cannot be null!");
    27         }
    28         // shield us from Date's mutability
    29         this.from = (Date) from.clone();
    30         this.to = (Date)to.clone();
    31         if (from.compareTo(to) >= 0) {
    32             throw new IllegalArgumentException("'from' must be lower than 'to'!");
    33         }
    34     }
    35     
    36     /** The length of the interval in milliseconds 
    37      * 
    38      * @return amount of milliseconds between 'from' and 'to' dates.
    39      */
    40     public long getLength() {
    41         return to.getTime() - from.getTime();
    42     }
    43 }
    44 // END: interval.api