Effective Java 15 Minimize mutability
Use immutable classes as much as possible instead of mutable classes.
Advantage
- Easy to design, implement and use than mutable classes.
- Less prone to error and more secure.
- Immutable objects are simple.
- Immutable objects are inherently thread-safe; they require no synchronization.
- Immutable objects and their internals can be shared freely between threads.
- Immutable calss can provide static factories that cache frequently requested instances to avoid creating new instances.
- 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:
- Don't provide any methods that modify the object's state.
- Ensure that the class can't be extended.
- Make all fields final.
- Make all fields private.
/**
* 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的更多相关文章
- 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 ...
- 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 ...
- 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 ...
- 《Effective Java》读书笔记 - 4.类和接口
Chapter 4 Classes and Interfaces Item 13: Minimize the accessibility of classes and members 一个好的模块设计 ...
- Effective Java 第三版——15. 使类和成员的可访问性最小化
Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...
- Effective Java Chapter4 Classes and Interface
MInimize the accessibility of classes and members 这个叫做所谓的 information hiding ,这么做在于让程序耦合度更低,增加程序的健壮性 ...
- Effective Java 目录
<Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...
- 【Effective Java】阅读
Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Obje ...
- Effective Java通俗理解(持续更新)
这篇博客是Java经典书籍<Effective Java(第二版)>的读书笔记,此书共有78条关于编写高质量Java代码的建议,我会试着逐一对其进行更为通俗易懂地讲解,故此篇博客的更新大约 ...
随机推荐
- Android学习笔记之蓝牙通信...
PS:最近同学问我蓝牙的事,因此自己也就脑补了一下蓝牙... 学习内容: 1.如何实现蓝牙通信技术... 蓝牙通信其实是手机里很常用的一种通信方式,现在的手机中是必然存在蓝牙的,蓝牙通信也是有一部 ...
- Android 学习笔记 BroadcastReceiver广播...
PS:不断提升自己,是件好事... 学习内容: 1.BroadcastReceiver的使用.. 2.通过BroadcastReceiver去启动Service... 1.BroadcastRecei ...
- mysql-5.6.14-winx64免安装配置
MySQL5.6.11安装步骤(Windows7 64位) 1. 下载MySQL Community Server 5.6.14 2. 解压MySQL压缩包 将以下载的MySQL压缩包解压到自定义目录 ...
- MVC学习笔记索引帖
[MVC学习笔记]1.项目结构搭建及单个类在各个层次中的实现 [MVC学习笔记]2.使用T4模板生成其他类的具体实现 [MVC学习笔记]3.使用Spring.Net应用IOC(依赖倒置) [MVC学习 ...
- 引入js和css文件的总结
1.用script标签引入javascript时,浏览器对于javascript的加载某些是并行的,某些是串行的,如IE8,Chorme2和firefox3都是串行加载的. 2.charset编码也就 ...
- 查询自己电脑的IP
1.怎样查询电脑的IP 1)运用dos命令 在运行窗体上输入cmd,进入dos命令窗体,输出ipconfig/all命令,找到自己的IP地址 上面所圈出的就是本机IP地址 2) 进入“网络和共享中心” ...
- ArrayList、Vector、HashMap、HashTable、HashSet的默认初始容量、加载因子、扩容增量
这里要讨论这些常用的默认初始容量和扩容的原因是: 当底层实现涉及到扩容时,容器或重新分配一段更大的连续内存(如果是离散分配则不需要重新分配,离散分配都是插入新元素时动态分配内存),要将容器原来的数据全 ...
- Windows程序控件升级==>>构建布局良好的Windows程序
01.菜单栏(MenuStrip) 01.看看这就是menuStrip的魅力: 02.除了一些常用的属性(name.text..)外还有: 03.有人会问:上图的快捷键: 方法: 方式一:1.设置菜单 ...
- LINUX重启MYSQL的命令
LINUX重启MYSQL的命令 标签: mysqllinuxservice脚本web服务server 2010-06-25 10:21 62152人阅读 评论(0) 收藏 举报 分类: Linux( ...
- Web前端小白入门指迷
前注:这篇文章首发于我自己创办的服务于校园的技术分享 [西邮 Upper -- 004]Web前端小白入门指迷,写得很用心也就发在这里. 大前端之旅 大前端有很多种,Shell 前端,客户端前端,Ap ...