zoukankan      html  css  js  c++  java
  • Effective Java 39 Make defensive copies when needed

    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 (Item 38), 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.

       

  • 相关阅读:
    给linux用户分配docker权限
    alpine安装docker
    linux开机自启动配置
    virtualbox vdi硬盘扩容
    树莓派更新软件源的脚本
    原生js选中下拉框中指定值
    linux环境tomcat开启远程调试
    Vue2 和 Yii2 进行前后端分离开发学习
    httpd.conf文件中找不到Deny from all这句,怎么配置多站点
    yii2.0 advanced 学习教程
  • 原文地址:https://www.cnblogs.com/haokaibo/p/make-defensive-copies-when-needed.html
Copyright © 2011-2022 走看看