Effective_Java读后感(方法)

         第23条,检查参数有效性。在类中检查参数有效性还是很必要的。根据相应的错误显示相应的错误信息更为必要。这么做,一、能很快结束当前程序。有错误,就到此为止。二、方便查找错误。如果错误参数在此时不报错,那么给后面的代码留下一个雷。不定什么时候炸了,还不知道因为什么炸的。

         第24条,需要时使用保护性拷贝。以前真没意识到偷天换日如此厉害。Java是一种安全性的语言,但是即使在一门安全性的语言中,你也需要保护性的设计程序。假使类的客户会尽一切手段来破坏类的约束条件,在这样的前提下必须保护性的设计程序。比如下面一则程序:

public  final  class Period{
    public Period(Date start,Date end){
        if(start.compareTo(end)>0){
           throw new IllegalArgumentException(start + "after" + end);
        }
        this.start = start;
        this.end = end;
    }

    public Date start(){
        return start;
    }
    
    public Date end(){
        return end;
    }
}

   乍一看,这段代码没什么问题,这个类是非可变的,还做了时间顺序的判断。可是一意识到Date对象本身可变,就知道这个参数的约束性很容易被违反。看下面的调用就知道问题了。

     Date start = new Date();
     Date end = new Date();
     Period p = new Period(start, end);
     start.setYear(78);

 

     为了免受这种攻击,所以对该类的构造函数的每个参数进行保护性拷贝(defensive copy)是必要的。代码如下:

    

    public Period(Date start, Date end){
           this.start = new Date(start.getTime());
           this.end = new Date(s.getTime());
           if(this.start.compareTo(this.end)>0)
               throw new IllegalArgumentException(start + "after" + end);
    }

 

你可能感兴趣的:(effective)