Tuesday, October 19, 2010

Immutable objects

An immutable object is an object which state is guaranteed to stay identical over its entire lifetime. While it is perfectly possible to implement immutability without final, its use makes that purpose explicit, to the human (the software developer) and the machine (the compiler).
Immutable objects carry some very desirable characteristics:
  • they are simple to understand and easy to use
  • they are inherently thread-safe: they require no synchronization
  • they make great building blocks for other objects
Clearly final is going to help us define immutable objects. First in labelling our object as immutable, which makes it simple to use and understand by other programmers. Second in guaranteeing that the object's state never changes, which enable the thread-safe property: thread concurrency issues are relevant when one thread can change data while another thread is reading the same data. Because an immutable object never changes its data, synchronizing access to it is not needed. Create an immutable class by meeting all of the following conditions:
  1. Declare all fields private final.
  2. Set all fields in the constructor.
  3. Don't provide any methods that modify the state of the object; provide only getter methods (no setters).
  4. Declare the class final, so that no methods may be overridden.
  5. Ensure exclusive access to any mutable components, e.g. by returning copies.

No comments:

Post a Comment