Wednesday, January 16, 2008

Making an object Immutable.

Definition: Immutable objects are those whose state(i.e object data) cannot change once the object has been constructed.

Making an object immutable:

1. Make the class final
2. Make the constructor parameterized, so that we need not allow setter methods
3. Make all fields final and private
4. Provide getter methods for retrieving values of fields.

Example:

public final class XYZ{

private final String name;

//constructor
public XYZ(String paramName){
name=paramName;

}

//getter method
public String getName(){
return name;

}

}

Important: Note that javadoc 1.4 includes the -tag option, whereby simple custom tags may be defined. One might define an @is.Immutable tag, for example, to document a class as being immutable

Use of immutable objects?

We have objects of type reference and value in java. All value objects should be immutable. Why, what is the point in making it immutable?

Let's solve this by considering an example:

Case 1: If value objects were not immutable
We have two objects Person A and Person B, sharing one value object, let's say date of birth. If this value object were not immutable, then when we update the date of birth of 'Person A', then 'Person B''s date of birth is also changed.

Case 2: If value objects are immutable (which is true):
In this case, we can easily understand that, if there is a date value object being accessed by 'Person A', and 'Person B' also wants a date object, then a new object is created, which is used specifically by 'Person B' only.

Excerpt from UML distilled by Martin Fowler - "In other words, you should not be able to take a date object of 1-Jan-99 and change the same date object to be 2-Jan-99. Instead, you should create a new 2-Jan-99 object and link to that first object. The reason is that if the date were shared, you would update another object's date in an unpredictable way."