package effectivejava.creatinganddestoyingobjects;


import java.util.*;
/**
* This creates a lot of unnecessary duplicate objects. See below for the correct way
*
*
*/
public class Item4Defective {
    private final Date birthDate;

    public Item4Defective( Date birthDate ) {
        this.birthDate = birthDate;
    }

    // DO NOT do this!!!
    public boolean isBabyBoomer() {
        Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
        gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0);
        Date boomStart = gmtCal.getTime();
        gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0);
        Date boomEnd = gmtCal.getTime();
        return birthDate.compareTo(boomStart) >= 0 && birthDate.compareTo(boomEnd) < 0;
    }

}

===========================================================

package effectivejava.creatinganddestoyingobjects;

import java.util.*;

/**
* Does not create unnecessary objects
*
*
*/
public class Item4Correct {
    private final Date birthDate;

    public Item4Correct( Date birthDate ) {
        this.birthDate = birthDate;
    }

    /**
    * The starting and ending dates of the baby boom.
    */
    private static final Date BOOM_START;
    private static final Date BOOM_END;

    static {
        Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
        gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0);
        BOOM_START = gmtCal.getTime();
        gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0);
        BOOM_END = gmtCal.getTime();
    }

    public boolean isBabyBoomer() {
        return birthDate.compareTo(BOOM_START) >= 0 && birthDate.compareTo(BOOM_END) < 0;
    }



}

Hosted by www.Geocities.ws

1