Use immutable classes as much as possible instead of mutable classes.

Advantage

  1. Easy to design, implement and use than mutable classes.
  2. Less prone to error and more secure.
  3. Immutable objects are simple.
  4. Immutable objects are inherently thread-safe; they require no synchronization.
  5. Immutable objects and their internals can be shared freely between threads.
  6. Immutable calss can provide static factories that cache frequently requested instances to avoid creating new instances.
  7. Immutable objects make great building blocks for other objects.(eg. Use immutable object as the key of map or set colletion)  

Disadvantage

Immutable classes require a separate object for each distinct value which may be costly.

Principles:

  1. Don't provide any methods that modify the object's state.
  2. Ensure that the class can't be extended.
  3. Make all fields final.
  4. Make all fields private.
Ensure exclusive access to any mutable components.  

/**

* Example code for Minimize mutability

*/

package com.effectivejava.classinterface;

/**

* @author Kaibo

*

*/

public final class Complex {

private final double re;

private final double im;

public Complex(double re, double im) {

this.re = re;

this.im = im;

}

// Accessors with no corresponding mutators

public double realPart() {

return re;

}

public double imaginaryPart() {

return im;

}

public Complex add(Complex c) {

return new Complex(re + c.re, im + c.im);

}

public Complex subtract(Complex c) {

return new Complex(re - c.re, im - c.im);

}

public Complex multiply(Complex c) {

return new Complex(re * c.re - im * c.im, re * c.im + im * c.re);

}

public Complex divide(Complex c) {

double tmp = c.re * c.re + c.im * c.im;

return new Complex((re * c.re + im * c.im) / tmp, (im * c.re - re* c.im)/ tmp);

}

@Override

public boolean equals(Object o) {

if (o == this)

return true;

if (!(o instanceof Complex))

return false;

Complex c = (Complex) o;

// See page 43 to find out why we use compare instead of ==

return Double.compare(re, c.re) == 0 && Double.compare(im, c.im) == 0;

}

@Override

public int hashCode() {

int result = 17 + hashDouble(re);

result = 31 * result + hashDouble(im);

return result;

}

private int hashDouble(double val) {

long longBits = Double.doubleToLongBits(re);

return (int) (longBits ^ (longBits >>> 32));

}

@Override

public String toString() {

return "(" + re + " + " + im + "i)";

}

/**

* @param args

*/

public static void main(String[] args) {

Complex c1 = new Complex(1.0, 2.0);

Complex c2 = new Complex(1.0, 2.0);

Complex c3 = new Complex(3.0,4.0);

System.out.printf("c1.equals(c2) = %s%n", c1.equals(c2));

System.out.printf("c1.equals(c3) = %s%n",c1.equals(c3));

System.out.printf("c1 + c2 = %s%n", c1.add(c2));

System.out.printf("c1 - c2 = %s%n", c1.subtract(c2));

System.out.printf("c1 * c2 = %s%n", c1.multiply(c2));

System.out.printf("c1 / c2 = %s%n", c1.divide(c2));

}

}

Note:

You can use alternative immutable implementation to not permit class to be subclassed instead of use final decorate to the class. Just use the static factory method and private constructor to constrain this which enable the client outside the package to use this class freely and providing the extensibility for caching.

// Immutable class with static factories instead of constructors

public class Complex {

private final double re;

private final double im;

private Complex(double re, double im) {

this.re = re;

this.im = im;

}

public static Complex valueOf(double re, double im){

return new Complex(re, im);

}

public static Complex valueOfPolar(double r, double theta) {

return new Complex(r * Math.cos(theta), r * Math.sin(theta));

}

... // Remainder unchanged

}

BigInteger and BigDecimal are not final

If you write a class whose security depends on the immutability of a BigInteger or BigDecimal argument from an untrusted client, you must check to see that the argument is a "real" BigInteger or BigDecimal, rather than an instance of an untrusted subclass. If it is the latter, you must defensively copy it under the assumption that it might be mutable (Item 39)

public static BigInteger safeInstance(BigInteger val) {

if (val.getClass() != BigInteger.class)

return new BigInteger(val.toByteArray());

return val;

}

Serializability.

If you choose to have your immutable class implement Serializable and it contains one or more fields that refer to mutable objects, you must provide an explicit readObject or readResolve method, or use the ObjectOutputStream.writeUnshared and ObjectInputStream.readUnsharedmethods, even if the default serialized form is acceptable. Otherwise an attacker could create a mutable instance of your not quite-immutable class. This topic is covered in detail in Item76.

Summary

If a class cannot be made immutable, limit its mutability as much as possible. make every field final unless there is a compelling reason to make it non-final.

Effective Java 15 Minimize mutability的更多相关文章

  1. Effective Java 13 Minimize the accessibility of classes and members

    Information hiding is important for many reasons, most of which stem from the fact that it decouples ...

  2. Effective Java 45 Minimize the scope of local variables

    Principle The most powerful technique for minimizing the scope of a local variable is to declare it ...

  3. Effective Java Index

    Hi guys, I am happy to tell you that I am moving to the open source world. And Java is the 1st langu ...

  4. 《Effective Java》读书笔记 - 4.类和接口

    Chapter 4 Classes and Interfaces Item 13: Minimize the accessibility of classes and members 一个好的模块设计 ...

  5. Effective Java 第三版——15. 使类和成员的可访问性最小化

    Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...

  6. Effective Java Chapter4 Classes and Interface

    MInimize the accessibility of classes and members 这个叫做所谓的 information hiding ,这么做在于让程序耦合度更低,增加程序的健壮性 ...

  7. Effective Java 目录

    <Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...

  8. 【Effective Java】阅读

    Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Obje ...

  9. Effective Java通俗理解(持续更新)

    这篇博客是Java经典书籍<Effective Java(第二版)>的读书笔记,此书共有78条关于编写高质量Java代码的建议,我会试着逐一对其进行更为通俗易懂地讲解,故此篇博客的更新大约 ...

随机推荐

  1. Windows Azure Web Site (17) 设置Web App TimeOut时间

    <Windows Azure Platform 系列文章目录> 我们在开发Azure Web App的时候,如果页面加载时间过长,可能需要设置Time Out时间. 在这里笔者简单介绍一下 ...

  2. 转载:第二弹!全球首个微信小程序(应用号)开发教程!通宵吐血赶稿!每日更新!

    今天一波三折,承受了超出预料的压力和煎熬,最后还是决定继续放出我的更新教程.我想我一没有泄露公司的代码,二没有提供泄露开发工具下载,只是从程序猿角度写了篇开发日志.我已经做好了最坏的准备,就算放弃这份 ...

  3. mysql主从复制显示正常,数据没同步现象。

    当时在一个服务器上开启了多实例,主从复制结构图如下: 当时在192.168.10.3的服务器上用show slave status;显示的是正常的复制的,两个线程都为yes,并且读与写的pos也一直在 ...

  4. 【Win10】探索 Windows 10 10586 之 JumpList(跳转列表)

    Windows 10 10586 出来了也挺久的了,应该大部分都从 10240 升级到这个版本了.在 10586 中,微软添加了 200 多个新的 API,具体 API 的变动,大家可以点击下面这个链 ...

  5. Hyperion Business Modeling for Microsoft Windows (32-bit)

    介质包搜索 常见问题    说明   复查 许可证列表 以确定需要下载的产品程序包. 请选择产品程序包和平台,然后单击“查找”. 如果只有一项结果,则可以看到下载页.如果有多个结果,请选择一个,然后单 ...

  6. Linq之group子句

    在Linq查询语句中,group子句主要作用是对查询的结果集进行分组.并返回元素类型为IGrouping<TKey,TElement>的对象序列. 下面我们在代码实例中创建一个GroupQ ...

  7. wget进行整站下载

    wget加上参数之后,即可成为相当强大的下载工具. wget -r -p -np -k http://xxx.com/abc/ -r,  --recursive(递归)          specif ...

  8. iOS UITableview

    1. UITableView //去除tableviews的点击效果 cell.selectionStyle = UITableViewCellSelectionStyleNone;    //隐藏t ...

  9. S2 易买网总结

    易买网项目总结 --指导老师:原玉明 不知不觉,又到了S2结业的时间了,S1的项目KTV项目还历历在目.一路走来,感觉时间过的好快,我们离就业也越来越近... 展示: 1.主页面(首页) 01.商品分 ...

  10. 请用fontAwesome代替网页icon小图标

    1. 引言 网页小图标到处可见,如果一个网页都是干巴巴的文字和图片,而没有小图标,会显得非常简陋.下面的小图标,你是不是会经常用到? 你可能说——“我们用的都是彩色的,不是黑白的”——别着急,下面会讲 ...