不可变类应该是最终的? [英] immutable class should be final?

查看:103
本文介绍了不可变类应该是最终的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这篇文章中说:


将类设为final是因为它是不可变的,这是一个很好的理由。

Making a class final because it is immutable is a good reason to do so.

我对此感到有些困惑......我理解不变性对于线程安全性和简单性的POV是一件好事,但似乎这些问题与可扩展性有些正交。那么,为什么不变性是让一个类最终成为一个很好的理由呢?

I'm a bit puzzled by this... I understand that immutability is a good thing from the POV of thread-safety and simplicity, but it seems that these concerns are somewhat orthogonal to extensibility. So, why is immutability a good reason for making a class final?

推荐答案

这个解释在有效一书中给出Java'

The explanation for this is given in the book 'Effective Java'

在Java中考虑 BigDecimal BigInteger 类。

Consider BigDecimal and BigInteger classes in Java .

BigInteger 和<时,不可理解的类必须是有效的最终
。编写code> BigDecimal ,因此所有方法都可能被
覆盖。不幸的是,在保留向后兼容性的情况下,这无法得到纠正。

It was not widely understood that immutable classes had to be effectively final when BigInteger and BigDecimal were written, so all of their methods may be overridden. Unfortunately, this could not be corrected after the fact while preserving backward compatibility.

如果编写一个安全性取决于BigInteger或BigDecimal参数的不变性的类从不受信任的客户端,您必须检查该参数是否为真正的BigInteger或BigDecimal,而不是不受信任的子类的实例。如果是后者,则必须在假设它可能是可变的情况下进行防御性复制。

   public static BigInteger safeInstance(BigInteger val) {

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

    return new BigInteger(val.toByteArray());


       return val;

   }

如果你允许子类,它可能会破坏纯度不可变对象。

If you allow sub classing, it might break the "purity" of the immutable object.

这篇关于不可变类应该是最终的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆