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》,运行代码感受一下会理解更深刻喔。

你可能感兴趣的:(java,java,effective)