Wednesday, January 16, 2008

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."


No comments: