Monday, May 20, 2013

What is Immutable Class. Why would you choose it ? How would you make a class immutable ?

What is Immutable Object

When the state of object can not be changed after its construction then the object is called Immutable.

Why do we need it

Immutable objects are inherently thread-safe, thus help writing multi-threading code without much worries. Immutable questions are meant for multi-threading program. If someone is talking bout immutability then indirectly he is talking about multi-threaded context. Immutable classes are easy to understand, as they possess a single state, which is controlled by their constructor. Immutable objects are good candidate for hash keys because their hashcode can be cached and reused for better performance.

Which Objects should be Immutable

Immutable classes are ideal for representing ADT's (Abstract Data Type) value.
Joshua Bloch suggests that
"All classes should be designed to be immutable unless there is a specific reason not to do so"

Guidelines for Making a class Immutable

1. All fields should be declared final
2. Class itself is declared final so that the derived classes do not make it Mutable.
3. this reference should not be allowed to escape during object construction such as in anonymous inner classes (for example adding action listener)
4. Any field that contains reference to mutable objects (such as arrays, collections, StringBuffer, etc)
i. Are private
ii. Are never returned or exposed to the caller
iii. Are the only reference to the Objects that they refer
iv. Do not change the state of the referenced object after the construction.
v. If mutable fields must be returned to the caller, then a defensive copy should be returned so that the changes do not reflect in the inner data structure.

public List getList() {
     return Collections.unmodifiableList(list); <=== defensive copy of the mutable field before returning it to caller
vi. If a mutable Object is passed in the constructor (like an array), then Immutable class should first make a defensive copy of the mutable object before storing its reference.

No comments:

Post a Comment

Your comment will be published after review from moderator