What are the consequences of immutable classes with references to mutable classes?

Posted by glenviewjeff on Programmers See other posts from Programmers or by glenviewjeff
Published on 2011-06-22T18:33:40Z Indexed on 2011/06/23 0:32 UTC
Read the original article Hit count: 412

I've recently begun adopting the best practice of designing my classes to be immutable per Effective Java [Bloch2008]. I have a series of interrelated questions about degrees of mutability and their consequences.

I have run into situations where a (Java) class I implemented is only "internally immutable" because it uses references to other mutable classes. In this case, the class under development appears from the external environment to have state.

  1. Do any of the benefits (see below) of immutable classes hold true even by only "internally immutable" classes?

  2. Is there an accepted term for the aforementioned "internal mutability"? Wikipedia's immutable object page uses the unsourced term "deep immutability" to describe an object whose references are also immutable.

  3. Is the distinction between mutability and side-effect-ness/state important?


Josh Bloch lists the following benefits of immutable classes:

  • 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

© Programmers or respective owner

Related posts about best-practices

Related posts about concurrency