Showing posts with label Immutable Class. Show all posts
Showing posts with label Immutable Class. Show all posts

Wednesday, December 18, 2013

How to make a java class immutable

Most of us know about mutable and  immutable concept and advantages of immutable class in java.
But many of those think we can not make our own java class as immutable  and it is by pre defined. It is not true, we can make our own classes as immutable.
Any way as we discussing immutability concept I want to discuss the advantages of  immutability concept here.

Benefits 
Immutable classes
  1. Are automatically thread-safe and have no synchronization issues
  2. Do not need a copy constructor
  3. Do not need an implementation of clone
  4. Allow hashcode to use lazy initialization, and to cache its return value
  5. Do not need to be copied defensively when used as a field
  6. Make good Map keys  and set elements (these objects must not change state while in the collection)
Making Class as Immutable 
Java Documentation as itself some notes on this concept you can find that here  

1) Don’t provide “setter” methods  
Setter methods are meant to change the state of object and this is what we want to prevent here.
2) Make all fields final and private 
Fields declared private will not be accessible outside the class and making them final will ensure the even accidentally you can not change them
3) Declare class as final
 Don’t allow subclasses to override methods
4) Attention with mutable instance variables in class
Always remember that you can have either mutable  or immutable instance variables, identify them and return new objects with copied content for all mutable objects. Immutable variables can be returned safely without extra effort.

Example :

Tha 𝗔𝗣𝗜 Design 𝗛𝗮𝗻𝗱𝗯𝗼𝗼𝗸

 Here is the 𝟮𝟬𝟮𝟲 𝗔𝗣𝗜 𝗛𝗮𝗻𝗱𝗯𝗼𝗼𝗸 broken down by architecture: 𝟭. 𝗧𝗵𝗲 "𝗥𝗲𝗾𝘂𝗲𝘀𝘁-𝗥𝗲𝘀𝗽𝗼𝗻𝘀𝗲" 𝗧𝗿𝗶𝗼: ...