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