`
d02540315
  • 浏览: 32290 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
最近访客 更多访客>>
社区版块
存档分类
最新评论

Defensive copying

 
阅读更多
A mutable object is simply an object which can change its state after construction. For example, StringBuilder and Date are mutable objects, while String and Integer are immutable objects.

A class may have a mutable object as a field. There are two possible cases for how the state of a mutable object field can change :

    * its state can be changed only by the native class - the native class creates the mutable object field, and is the only class which is directly aware of its existence
    * its state can be changed both by the native class and by its callers - the native class simply points to a mutable object which was created elsewhere

Both cases are valid design choices, but you must be aware of which one is appropriate for each case.

If the mutable object field's state should be changed only by the native class, then a defensive copy of the mutable object must be made any time it is passed into (constructors and set methods) or out of (get methods) the class. If this is not done, then it is simple for the caller to break encapsulation, by changing the state of an object which is simultaneously visible to both the class and its caller.

Example

Planet has a mutable object field fDateOfDiscovery, which is defensively copied in all constructors, and in getDateOfDiscovery. Planet represents an immutable class, and has no set methods for its fields. Note that if the defensive copy of DateOfDiscovery is not made, then Planet is no longer immutable!

import java.util.Date;

/**
* Planet is an immutable class, since there is no way to change
* its state after construction.
*/
public final class Planet {

  public Planet (double aMass, String aName, Date aDateOfDiscovery) {
     fMass = aMass;
     fName = aName;
     //make a private copy of aDateOfDiscovery
     //this is the only way to keep the fDateOfDiscovery
     //field private, and shields this class from any changes that 
     //the caller may make to the original aDateOfDiscovery object
     fDateOfDiscovery = new Date(aDateOfDiscovery.getTime());
  }

  /**
  * Returns a primitive value.
  *
  * The caller can do whatever they want with the return value, without 
  * affecting the internals of this class. Why? Because this is a primitive 
  * value. The caller sees its "own" double that simply has the
  * same value as fMass.
  */
  public double getMass() {
    return fMass;
  }

  /**
  * Returns an immutable object.
  *
  * The caller gets a direct reference to the internal field. But this is not 
  * dangerous, since String is immutable and cannot be changed.
  */
  public String getName() {
    return fName;
  }

//  /**
//  * Returns a mutable object - likely bad style.
//  *
//  * The caller gets a direct reference to the internal field. This is usually dangerous, 
//  * since the Date object state can be changed both by this class and its caller.
//  * That is, this class is no longer in complete control of fDate.
//  */
//  public Date getDateOfDiscovery() {
//    return fDateOfDiscovery;
//  }

  /**
  * Returns a mutable object - good style.
  * 
  * Returns a defensive copy of the field.
  * The caller of this method can do anything they want with the
  * returned Date object, without affecting the internals of this
  * class in any way. Why? Because they do not have a reference to 
  * fDate. Rather, they are playing with a second Date that initially has the 
  * same data as fDate.
  */
  public Date getDateOfDiscovery() {
    return new Date(fDateOfDiscovery.getTime());
  }

  // PRIVATE //

  /**
  * Final primitive data is always immutable.
  */
  private final double fMass;

  /**
  * An immutable object field. (String objects never change state.)
  */
  private final String fName;

  /**
  * A mutable object field. In this case, the state of this mutable field
  * is to be changed only by this class. (In other cases, it makes perfect
  * sense to allow the state of a field to be changed outside the native
  * class; this is the case when a field acts as a "pointer" to an object
  * created elsewhere.)
  */
  private final Date fDateOfDiscovery;
}


分享到:
评论

相关推荐

    Defensive Security Handbook: Best Practices for Securing Infrastructure

    Defensive Security Handbook: Best Practices for Securing Infrastructure by Lee Brotherston English | 3 Apr. 2017 | ASIN: B06Y18XC5Y | 268 Pages | AZW3 | 3.88 MB Despite the increase of high-profile ...

    防御式编程 Defensive Programming.PPT完整版(精品课件)

    防御式编程 Defensive Programming.PPT完整版(精品课件) 大纲: 保护程序免遭非法输入数据的破坏 断言 错误处理技术 异常 隔离程序 辅助调试代码

    难得的经典——《Defensive Programming for RedHat Enterprise Linux》

    ### 难得的经典——《Defensive Programming for Red Hat Enterprise Linux》 #### 摘要与背景 在软件开发领域,安全性和稳定性是至关重要的。随着互联网的发展,网络安全威胁日益严重,对软件的安全性提出了更高...

    Defensive Security Handbook(O'Reilly,2017) (三种格式pdf,azw3,epub)

    内容简介: Despite the increase of high-profile hacks, record-breaking data leaks, and ransomware attacks, many organizations don’t have the budget to establish or outsource an information security ...

    Defensive_Database_Programming_with_SQL_Server

    ### 防御性数据库编程与SQL Server #### 引言 《防御性数据库编程与SQL Server》一书由Alex Kuznetsov撰写,并由Hugo Kornelis进行了技术审稿,首次由Simple Talk Publishing出版于2010年。本书主要探讨了在SQL ...

    Java Defensive Programming-开源

    Java防御性编程是一种编程策略,旨在提前预防程序中可能的错误和异常,从而提高软件的稳定性和可靠性。在Java中,防御性编程通常通过注释、异常处理、数据验证和健壮的错误处理来实现。开源社区提供了许多工具和库来...

    Defensive Security Handbook(O'Reilly,2017)

    Despite the increase of high-profile hacks, record-breaking data leaks, and ransomware attacks, many organizations don’t have the budget to establish or outsource an information security (InfoSec) ...

    defensive database programming

    本书《Defensive Database Programming with SQL Server》由Alex Kuznetsov撰写,深入探讨了如何在SQL Server环境中实施防御性编程策略。 ### 一、基本防御性数据库编程技术 #### 1. 减少代码漏洞 - **定义假设**...

    Defensive.Database.Programming.with.SQL.Server

    《防守型数据库编程与SQL Server》一书由Alex Kuznetsov撰写,是关于如何在SQL Server环境中构建更安全、更稳定的应用程序的深入指南。本书聚焦于防御性编程技术,旨在帮助数据库开发者预见到可能的问题,并采取措施...

    The practice of defensive school psychology

    The practice of defensive school psychology THE PRACTICE OF DEFENSIVE SCHOOL PSYCHOLOGY DONALD A. LUPIANI Riverdale Country School Recent legal developments promise to bring school ...

    matlab导入excel代码-utl_sas_defensive_programming_and_error_checking:SAS防御性

    matlab导入excel代码utl_sas_defensive_programming_and_error_checking SAS防御性编程和错误检查关键字:sas sql连接合并合并大数据分析宏oracle teradata mysql sas社区stackoverflow统计信息人工智慧AI Python R ...

    Offensive-Defensive-Weight:进攻防守重量-熊体育分析

    "Offensive-Defensive-Weight"(进攻防守权重)是一个专门用于评估球队或运动员在比赛中的攻防表现的数据模型。这个概念通常应用于篮球、足球等团队运动,通过量化每个球员或队伍在进攻和防守方面的贡献来帮助教练组...

    secure-coding-defensive

    安全编码防御项目 这是Vulgar Bandidtos(Benjamin Daschel,Jacob Leque和Lander Brandt)的Java项目。 编译中 mvn clean compile assembly:single 这将在target目录中生成一个具有所有依赖项的.jar文件。...

    Cyber Operations(Apress,2015)

    This book focuses on networks and real attacks, offers extensive coverage of offensive and defensive techniques, and is supported by a rich collection of exercises and resources. You'll learn how to...

    defensive-ex-mxli417

    请注意:我应该怎么办: 除了练习中指定的以外,不要使用任何外部软件包。 总是允许使用tidyverse软件包, checkmate和testthat 。 至少,您的代码应遵循Hadley Wickham的的准则,并进行充分注释。...

    Splunk-Defensive-Analysis:具有三个相关CVE的Splunk软件报告

    Splunk-防守分析 关于通过进行数据管理的科学论文,其中包括三个相关的CVE漏洞分析,旨在强调Splunk的可靠性。 该项目是作为意大利卡塔尼亚大学的互联网安全关系进行的。 请阅读文档(意大利语) ...

    DefensiveDatabaseProgrammingWithSQLServer.pdf 英文原版

    Defensive Database Programming With SQL Server

    Defensive-Measures-Add-on-Wiki:目前正在开发的防御措施附加组件Wiki

    防御措施,在Wiki上添加 专门用于我当前正在开发的附件的Wiki。 该wiki使用laravel 5.6创建,允许访问者查看该附加组件的所有详细信息,从安装到每个新添加的物品的制作配方,甚至是即将到来的更新。...

Global site tag (gtag.js) - Google Analytics