Thursday, June 28, 2007

Immutable Objects In Java

What is an Immutable Object ?

An immutable object is an object that does not change its state once its created .Java has a number of inbuilt classes that provide that functionality e.g String , Integer etc..

So how do you create an immutable object :
  • Remove or make setters less accessible.
  • Preveting methods from getting overriden.
  • Make all fields final.
  • Make defensive copies of mutable objects.
  • Do not provide a clone method
  • Do not provide a copy constructor
  • return a fuctional object
Returning a functional object means applyting a function on the parameters of a method and returning the function rather than calculating the function and returning the value . e.g

public class Complex {
public Complex(int real, int imaginery){
this.real = real;
this.imaginery = imaginery;
}

public Complex add(Complex left , Complex right) {

// fuctional return
return new Complex(left.real + right.real , left.imaginery + right.imaginery);
}
}

The advantage of having an immutable class is that its thread safe.
The disadvantage being creating many new objects for different operations can lead to memory bloat

No comments: