博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Effective Java 39 Make defensive copies when needed
阅读量:4589 次
发布时间:2019-06-09

本文共 1452 字,大约阅读时间需要 4 分钟。

Principle

  1. It is essential to make a defensive copy of each mutable parameter to the constructor.
  2. Defensive copies are made before checking the validity of the parameters (), and the validity check is performed on the copies rather than on the originals.  

    // Repaired constructor - makes defensive copies of parameters

    public Period(Date start, Date end) {

    this.start = new Date(start.getTime());

    this.end = new Date(end.getTime());  

    //Make the defensive copies of the parameters before using them.

    if (this.start.compareTo(this.end) > 0)

    throw new IllegalArgumentException(start +" after "+ end);

    }

       

    TOCTOU = time of check/ time of use.

  3. Do not use the clone method to make a defensive copy of a parameter whose type is subclassable by untrusted parties.
  4. Return defensive copies of mutable internal fields.  

    // Repaired accessors - make defensive copies of internal fields

    public Date start() {

    return new Date(start.getTime());

    }

    public Date end() {

    return new Date(end.getTime());

    }  

Summary

If a class has mutable components that it gets from or returns to its clients, the class must defensively copy these components. If the cost of the copy would be prohibitive and the class trusts its clients not to modify the components inappropriately, then the defensive copy may be replaced by documentation outlining the client's responsibility not to modify the affected components.

   

转载于:https://www.cnblogs.com/haokaibo/p/make-defensive-copies-when-needed.html

你可能感兴趣的文章
c# 控制台输入和输出
查看>>
c# 构造函数举例
查看>>
c# 类成员的可访问性
查看>>
c# 私有构造函数
查看>>
c# 构造函数
查看>>
c# 静态方法
查看>>
c# 析构函数
查看>>
c# 字段成员
查看>>
c# 静态变量
查看>>
c# 值传递
查看>>
c# 输出参数-out
查看>>
c# 静态构造函数
查看>>
c# 属性说明
查看>>
c# 方法成员
查看>>
c# 定义和调用索引器
查看>>
c# 引用参数-ref
查看>>
c# 多态
查看>>
c# 参数数组
查看>>
c# 虚属性
查看>>
c# 子类的声明
查看>>