Immutable Objects in Java

Posted by

Immutability of an object indicates that once an object is constructed with given values, its state and values cannot be altered. In case of any value change must result in new object creation.

Out of box Java offers some Immutable objects for instance java.lang.String, java.lang.Integer, java.lang.Float, java.math.BigDecimal.

Immutable objects make generally a good use in concurrent programming. The reliability is a key aspect in concurrent programming, so that corrupted data sets and objects may cause unwanted behaviors in applications.

Pros

  • Reliable and Atomic Data: The given data during the initialization of the immutable object is always the same, thus the data set is ensured and atomic. Furthermore, An Immutable object can be a good candidate to be the Key in Map collection,
  • Thread Safety/Concurrency: The content of an immutable object is valid and no method may cause an alteration of the state thus it is thread safe,
  • Garbage Collection: The garbage collectors can easily identify and make decisions on immutable objects.

Cons

  • Mass of objects: Allocating lots of new objects may cause to increase the memory allocation for modifications. This can be somehow manageable while employing a good model of java memory management.

Rules to define an Immutable Object:
Immutability of an object indicates that once an object is constructed with given values, its state and values cannot be altered. In case of any value change must result in new object creation.
Out of box Java offers some Immutable objects for instance java.lang.String, java.lang.Integer, java.lang.Float, java.math.BigDecimal.
Immutable objects make generally a good use in concurrent programming. The reliability is a key aspect in concurrent programming, so that corrupted data sets and objects may cause unwanted behaviors in applications.

Pros:
-Reliable and Atomic Data: The given data during the initialization of the immutable object is always the same, thus the data set is ensured and atomic. Furthermore, An Immutable object can be a good candidate to be the Key in Map collection,
-Thread Safety/Concurrency: The content of an immutable object is valid and no method may cause an alteration of the state thus it is thread safe,
-Garbage Collection: The garbage collectors can easily identify and make decisions on immutable objects,

Cons:
-Allocating lots of new objects may cause to increase the memory allocation for modifications. This can be somehow manageable while employing a good model of java memory management.

Rules to define an Immutable Object

1. Mark the designated immutable class as final; this will disallow the class to be subclasses or its methods to be overridden,
2. Mark all the fields with the final keyword and package access as private, this way fields will not be discoverable for other classes, as well as the values of fields will be forced to be initially set,
3. Mark the no arg constructor as private thus; creation of an empty valued object will be prevented,
4. Provide only one constructor and mark it as public to force callers to initialize all the fields,
5. Elimination of any methods that may change the state known as Setter Methods,
6. Last of all in case of having a mutable class as field member;
a. Mark it as final, so that its value can be assigned once only,
b. Disallow to have methods that will change the object state,
c. Perform to clone of the object not the object reference via getter methods, thus the alteration will be prevented.

Sample Immutable Object

import java.util.Collections;
import java.util.Date;
import java.util.List;

//Rule #1
public final class Student {
    /**
     * Immutable Object Field Declarations
     */
  //Rule #2
    private final String name;
    private final String lastName;
  //Rule #6a
    private final Date birthDate;
    private final List<String> classes;

    /**
     * Immutable Object Constructor Declarations
     */
  //Rule #3
    private Student() {
        this(null, null, null, null);
    }

  //Rule #4
    public Student(String name, String lastName, Date birthDate, List<String> classes) {
        this.name = name;
        this.lastName = lastName;
        this.birthDate = birthDate;
        this.classes = classes;
    }
  
  //Rule #5 and #6b- No setter methods exist

    /**
     * Immutable Object Getter Method Declarations
     */
    public String getName() {
        return name;
    }

    public String getLastName() {
        return lastName;
    }

  // Rule #6c
    public Date getBirthDate() {
        return (Date) birthDate.clone();
    }

    public List getClasses() {
        return Collections.unmodifiableList(classes);
    }
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *