samples/cloneproblem/src/org/apidesign/cloneproblem/Interval.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Thu, 30 Oct 2014 21:30:10 +0100
changeset 409 40cabcdcd2be
parent 368 e1089d423881
permissions -rw-r--r--
Updating to NBMs from NetBeans 8.0.1 as some of them are required to run on JDK8
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@369
    19
     * @throws IllegalArgumentException 
jtulach@369
    20
     *      if <code>from</code> is not less then <code>to</code>
jtulach@368
    21
     */
jtulach@368
    22
    public Interval(Date from, Date to) {
jtulach@368
    23
        if (from == null) {
jtulach@368
    24
            throw new IllegalArgumentException("'from' cannot be null!");
jtulach@368
    25
        }
jtulach@368
    26
        if (to == null) {
jtulach@368
    27
            throw new IllegalArgumentException("'to' cannot be null!");
jtulach@368
    28
        }
jtulach@368
    29
        // shield us from Date's mutability
jtulach@368
    30
        this.from = (Date) from.clone();
jtulach@368
    31
        this.to = (Date)to.clone();
jtulach@368
    32
        if (from.compareTo(to) >= 0) {
jtulach@369
    33
            throw new IllegalArgumentException(
jtulach@369
    34
                "'from' must be lower than 'to'!"
jtulach@369
    35
            );
jtulach@368
    36
        }
jtulach@368
    37
    }
jtulach@368
    38
    
jtulach@368
    39
    /** The length of the interval in milliseconds 
jtulach@368
    40
     * 
jtulach@368
    41
     * @return amount of milliseconds between 'from' and 'to' dates.
jtulach@368
    42
     */
jtulach@368
    43
    public long getLength() {
jtulach@368
    44
        return to.getTime() - from.getTime();
jtulach@368
    45
    }
jtulach@368
    46
}
jtulach@368
    47
// END: interval.api