Tuesday, May 9, 2017

immutable objects in java

In software programming, an immutable object is an object whose state cannot be modified after it is created.

How to make Immutable Object in Java


  • Make the class final.
  • Make all members final, set them explicitly, in a static block, or in the constructor.
  • Make all members private.
  • Do not expose any setter methods.
  • If the instance fields include references to mutable objects, then don't share references to the mutable objects. 
  • For getter methods which needs to return mutable objects, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.
  • Do not store references to external mutable objects passed to the constructor. Create copies, and store references to the copies. 


Advantage of Immutable Objects

Immutable Objects are ThreadSafe.
Value Objects are generally considered Immutable. In java String and all the Wrapper Classes like Integer, Boolean are immutable.
It enhances security and less bug when the object we are designing is not supposed to change value.
Immutable objects are better Keys and values for HashMap and HashSet respectively.



No comments :

Post a Comment