-1

Possible Duplicate:
Mutable vs immutable objects

I understand the pros and cons between Immutable object vs Mutable object, but how do you decide which one to go for when you come to design it.

The reason why I ask about it is because if it's mutable, you can reuse the object by just changing object back to the initial state as being efficient and in an economical way, so when you deal with multistep operations you can just reuse it over and over again. Whereas Immutable object performance is magnified when you perform a multistep operation since it generates a new object at every step. <- As far as memory is concern

Here's the example:

   //Mutable
   A a = new A();
   for(int j = 0 ; j < 1000 ; j++){
       a.setP1(j);
       //do something

   }

   //Immutable
   for(int j = 0 ; j < 1000 ; j++){
       A a = new A(j);
       //do something
   }

I know immutable objects are thead-safe, no synchronization required, simple, and share internals, but is there any particular reasons beside these ? and when should we make our class to final (immutable) ?

Community
  • 1
  • 1
peter
  • 8,333
  • 17
  • 71
  • 94

2 Answers2

1

Your reasoning for mutability is basically for object pooling vs creation. This is poor reason for making an object mutable, unless for some very specific reason it is very expensive to create, or the number of instances needs to be strictly controlled (like db connections and thread pools).

This was a technique used in the early days of Java that is now frowned upon. Let VM and garbage collector do its job and design your code for its use cases, ignoring this USUALLY 'imaginary' optimization.

Robin
  • 24,062
  • 5
  • 49
  • 58
0

I use immutable objects when:

  1. Working in a multithreaded environment, immutable objects are perfect for inter thread communications (messages)
  2. When an object does not hold a state where its member variables do not change over the life cycle of an application. Example, user credentials
GETah
  • 20,922
  • 7
  • 61
  • 103