mercredi 26 août 2015

Immutable classes in Java

First, let's start with a definition:

"An immutable object is an objet whose state cannot be modified after creation".


Pros:
* in a concurrent environnement, no way to bother if such an object is "held" and manipulated by different threads, as it won't be modified after creation: there is no way two different threads can share the same instance and "see" it in a different state

Cons:
* for large/complex objects, making a copy for every state modification can be costly and tedious
* for object with "an entity", it is more more intuitive to modified object's state than creating a new modified version of that object
* at the end, when modeling the real world, we think more easily in term of mutable object