Friday, August 9, 2013

Immutability - Custom Immutable Class

Java provides a mechanism in which you can create custom Immutable classes. By default, classes like String, Integer and other wrapper classes are immutable. So, what's the main advantage of a class being immutable -

a. An Immutable class is essentially thread-safe and is an ideal candidate for creating them in multi-threaded application.
b. Use of synchronized code is minimized in a multi-threaded application by use of immutable objects.
c. Since their states cannot be altered once they are created, they are excellent candidates as 'keys' for HashMaps.
d. Their re-usability is another good reason to create them, since it can be cached and can be set once in static initializers and used everywhere.

How to create an immutable class -

a. The Object has to be declared final.
b. All the members of the object has to be declared final. No setters method allowed.
c. Object should be constructed properly, i.e. should not result in leak during construction.

public final class ImmutableClass {
       private final String name;
       private final Integer age;
       private final Date dob;

       public ImmutableClass(name, age, dob) {
          this.name = name;
          this.age = age;
          this.dob = dob;
       }

       public String getName() {
         return name;
       }

       public Integer getAge() {
          return age;
       }

       //Mutable Object to prevent setting internal value - create a copy of the date and return a new date
       public Date getDob() {
          return Date(dob.clone());
       }            
}


No comments:

Post a Comment