`
iloveflower
  • 浏览: 76753 次
社区版块
存档分类
最新评论
  • iloveflower: 呵呵。好好学习。。。。。。。。。。。。
    java 读书
  • Eric.Yan: 看了一点,不过是电子版的……你这一说到提醒我了,还要继续学习哈 ...
    java 读书

Immutable objects

阅读更多
Immutable objects are simply objects whose state (the object's data) cannot change after construction. Examples of immutable objects from the JDK include String and Integer.
 Immutable objects greatly simplify your program, since they : 
■ are simple to construct, test, and use
■ are automatically thread-safe and have no synchronization issues
■ do not need a copy constructor
■ do not need an implementation of clone
■ allow hashCode to use lazy initialization, and to cache its return value
■ do not need to be copied defensively when used as a field
■ make good Map keys and Set elements (these objects must not change state while in the collection)
■ have their class invariant established once upon construction, and it never needs to be checked again
■always have "failure atomicity" (a term used by Joshua Bloch) : if an immutable object throws an exception, it's never left in an undesirable or indeterminate state
 Immutable objects have a very compelling list of positive qualities. Without question, they are among the simplest and most robust kinds of classes you can possibly build. When you create immutable classes, entire categories of problems simply disappear.
Make a class immutable by following these guidelines : 
■ensure the class cannot be overridden - make the class final, or use static factories and keep constructors private
■make fields private and final
■force callers to construct an object completely in a single step, instead of using a no-argument constructor combined with subsequent calls to setXXX methods (that is, avoid the Java Beans convention)
■do not provide any methods which can change the state of the object in any way - not just setXXX methods, but any method which can change state
■if the class has any mutable object fields, then they must be defensively copied when passed between the class and its caller
 In Effective Java, Joshua Bloch makes this compelling recommendation : 
"Classes should be immutable unless there's a very good reason to make them mutable....If a class cannot be made immutable, limit its mutability as much as possible."

It's interesting to note that BigDecimal is technically not immutable, since it's not final.
 
Example 


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;
}
 
 

Note that javadoc 1.4 includes the -tag option, whereby simple custom tags may be defined. One might define an @is.Immutable tag, for example, to document a class as being immutable.
 You might also consider defining your own tag interface for immutable objects
分享到:
评论

相关推荐

    Get Programming - Learn to code with Python.epub

    Lesson 24 - Mutable and immutable objects Lesson 25 - Working with lists Lesson 26 - Advanced operations with lists Lesson 27 - Dictionaries as maps between objects Lesson 28 - Aliasing and copying ...

    Programming in Objective-C 4th Edition

    Mutable Versus Immutable Objects 314 Mutable Strings 320 Array Objects 327 Making an Address Book 330 Sorting Arrays 347 Dictionary Objects 354 Enumerating a Dictionary 355 Set Objects 358 NSIndexSet ...

    Python 2.4 Quick Reference Card (Letter) (2007).pdf

    Mutable/Immutable Objects..................2 Namespaces.........................................2 Constants, Enumerations......................2 Flow Control........................................2 ...

    详细分析Python可变对象和不可变对象

    在 Python 中一切都可以看作为对象。每个对象都有各自的 id, type 和 value。 id: 当一个对象被创建后,它的 id 就不会在改变,这里...常见的不可变对象(immutable objects): Number: int, float, complex string t

    immutable-date:小日期包装器不要失去理智

    不可变日期 小日期包装器不要失去理智 安装 $ npm install --save ...the API is exactly shaped like the [Date](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) one.

    List-Objects-Types:List-Objects-Types 的只读发布历史

    名称List::Objects::Types - List::Objects::WithUtils 的基于 Type::Tiny ...has static_array => ( is => 'ro', isa => ImmutableArray, coerce => 1, default => sub { [qw/ foo bar /] });has my_hash => ( is => '

    python3.6.5参考手册 chm

    Python参考手册,官方正式版参考手册,chm版。以下摘取部分内容:Navigation index modules | next | Python » 3.6.5 Documentation » Python Documentation contents What’s New in Python ...

    OpenGL ES 3.0 Programming Guide, 2nd Edition

    compressed textures, sampler objects, immutable textures, pixel unpack buffer objects, and mipmapping Fragment shaders: multitexturing, fog, alpha test, and user clip planes Fragment operations: ...

    分位数滚动:快速,可组合的Pythonic分位数过滤器

    NumPy的滚动分位数 ... # declare a cascade of filters by a sequence of immutable description objects rq . LowPass ( window = 200 , portion = 100 , subsample_rate = 2 ), # the above takes a median

    Learning.Scala.Practical.Functional.Programming.for.the.JVM

    Why learn Scala? You don’t need to be a data scientist or distributed computing expert to appreciate this ... Objects, Case Classes and Traits Chapter 10. Advanced Typing Appendix A. Reserved Words

    Test_long_to_float.rar_ARGUMENT!

    @title Type of argument - double. Dalvik doens t distinguish 64-bits types FixedSizeList.rar Simple (mostly) fixed-size list of objects, which may be made immutable.

    Cocoa Fundamentals Guide

    Why Mutable and Immutable Object Variants? 90 Programming with Mutable Objects 91 Class Clusters 95 Without Class Clusters: Simple Concept but Complex Interface 95 With Class Clusters: Simple Concept ...

    ippo:不可变,静态类型,可克隆和可序列化的自动生成的纯老式PHP对象

    国际植保组织 不可变- with s一起使用with而不是setter 静态类型-您的工具喜欢它可克隆-没有参考共享可序列化-JSON,数组和字符串―自动生成的普通PHP对象。 :shield: 在其最严格的级别上验证lib的源代码及其生成的...

    Becoming Functional

    Immutable Variables 2 Nonstrict Evaluation 2 Statements 2 Pattern Matching 2 Functional Programming and Concurrency 3 Conclusion 3 2. First-Class Functions. . . . . . . . . . . . . . . . . . . . . . ....

    Effective C# (Covers C# 4.0) Mar 2010

    Employ immutable data types to promote multicore processing (see Item 20) Minimize garbage collection, boxing, and unboxing (see Items 16 and 45) Take full advantage of interfaces and delegates (see...

    Scala for the Impatient 2nd (完整英文第二版 带书签)

    13.2 Mutable and Immutable Collections 173 13.3 Sequences 174 13.4 Lists 175 13.5 Sets 177 13.6 Operators for Adding or Removing Elements 178 13.7 Common Methods 180 13.8 Mapping a Function 182 13.9 ...

    JavaScript权威指南(第6版,英文

    3.7 Immutable Primitive Values and Mutable Object References 44 3.8 Type Conversions 45 3.9 Variable Declaration 52 3.10 Variable Scope 53 4. Expressions and Operators . . . . . . . . . . . . . . . . ...

    monolite:静态类型的结构共享树修改器

    类型安全的结构共享树... Monolite接受Plain-Old JavaScript Objects并返回Plain-Old JavaScript Objects 。 访问器允许TypeScript理解您正在处理的类型,并提供完成和修饰,就好像您直接在这些对象上进行操作一样。

    Practical Java(中文版(繁体+简体))

    2 對象與相等性(Objects and Equality) 25 實踐8:區分reference type 和primitive type 25 實踐9:區分== 和 equals() 29 實踐10:不要倚賴equals()的缺省實現33 實踐11:實現equals()時必須深思熟慮 43 實踐12:...

    Professional C# 7 and .NET Core 2.0

    C# 7 focuses on data consumption, code simplification, and performance, with new support for local functions, tuple types, record types, pattern matching, non-nullable reference types, immutable ...

Global site tag (gtag.js) - Google Analytics