Wednesday 30 April 2008

So what do you understand by IMMUTABLE ?

but how do we define mutable, or immutable? I searched various Java texts but could not find a definition of what is meant by that. Let's try and define it for our use:

Immutable Class: A class where the state cannot be changed.

Simple enough, but what does state refer to? Is it a state descriptor of all the data members in the class? Or is it just the identity of the class? For example, let's consider the class Employee, which is part of the middle class ...

public class Employee {
  private final String name;
  private final double salary;
  private final Date dob;
  public Employee(String name, double salary, Date dob) {
    this.name = name;
    this.salary = salary;
    this.dob = dob;
  }
  public String getName() { return name; }
  public double getSalary() { return salary; }
  public Date getDOB() { return dob; }
}

Is the Employee class mutable?

If we say that the state consists of a combination of all the data members then the answer is "Yes". We need to be careful examining the object state here. Do you think its possible to change the object state from outside ?

If not then the object definition is immutable however if you are able to change then the object is not immutable?

General assumption is if the member variables are declared final and we only provide the accessers then the class is immutable. So let us use the above class in our code.

public class ImmutabilityTest {
  public static void main(String[] str) {
      Employee emp = new Employee(“john”, 10000, new Date());
    //lets fetch the emp date of birth;
        Date empdob = emp.getDOB();
    //so I got the reference to the final object stored within the
    //Employee object.
        
        empdob.setMonth(10);
        //can I do this ?
        //how about the state of the original object ?? 
        }
}

So I created the emp object and got the dob date object reference and changed the date value empdob.setMonth(10); so I am able to change the object state.

The key thing worth keeping in mind is the final keyword is making the refernce final. The objects state of members is still changeable through refernces.

How you would address such issues ?

You need to make sure that whenever you return the object, you return the copy of the object. E.g. modify the getDOB() in this case to do something like

public Date getDOB() { return dob.clone(); }

I am keeping the original reference within the object itself and returning the deep copy of the object to the caller.

0 comments: