1. 程式人生 > >Effective Java 第五條:避免建立不必要的物件

Effective Java 第五條:避免建立不必要的物件

反例:

public class Person {

    private final Date birthDate;

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

    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;
    }
}

對於上面方法中,如果檢查出生嬰兒是否在生育高峰期,每次呼叫此方法就要初始化Calender、Date物件。並且我們知道boomStart和boomEnd值始終是不變的,我們大可不必每次呼叫方法就初始化物件。建議修改如下:

正例:
public class PersonNew {
    private final Date birthDate;

    private static Date BOOM_START = null;
    private static Date BOOM_END = null;

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

    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;
    }
}

以上程式碼來自《Effective Java》,執行程式碼感受一下會理解更深刻喔。