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.


Benefits of Immutability

  • are simple to construct, test, and use
  • are automatically thread-safe and have no synchronization issues
  • don’t need a copy constructor
  • don’t need an implementation of clone
  • allow hashCode to use lazy initialization, and to cache its return value
  • don’t 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


Rules for Immutability

The following rules define a simple strategy for creating immutable objects.

  • don’t provide “setter” methods —methods that modify fields or objects referred to by fields.
  • make all fields final and private.
  • don’t allow sub classes to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.
  • don’t 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
  • don’t share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.
  • if the instance fields include references to mutable objects, don’t allow those objects to be changed







Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s