Thursday, December 9, 2010

Immutable Objects ?

What is an immutable object?

Immutable object is an object whose state cannot be changed or simply cannot be modified after its construction. That means once you instantiate an immutable object thats it you can never modify it.

There are many immutable classes provided by the Java platform. Examples are String, BigInteger, BigDecimal and primitive wrapper classes.

But why making classes immutable? There are many reasons,
  • Easy to design and implement
  • More secure and less error prone
  • Simple
  • Automatically thread-safe
  • Can be shared freely
The only disadvantage of immutable object can be the performance impact due to the creation of separate object for each and every distinct value.

So lets discuss the main objective of this post, how to create one? To make an immutable class you have to follow following rules,
  1. Make the class as final - ensures the class can not be overridden
  2. Mark fields as private and final - prevent from being modified directly
  3. Use constructor to construct the object completely - have to instantiate it in single line
  4. Remove any method which can change its state - state can not be changed
  5. Extra attention to mutable object fields (create new mutable object in any time passed into constructor or out of getter methods) - maintain immutability

Following is an example Employee class,
sample Employee immutable class


"Classes should be immutable unless there is a very good reason to make them mutable... If a class cannot be made immutable, limit its mutability as much as possible"
(By Joshua Bloch)



Cheers!