Saturday, August 23, 2014

EJ-15 Minimize Mutability

Ref: Effective Java by Joshua Bloch

An immutable class is simply a class whose instances can not be modified, all of the information contained in each instance is provided when it is created and is fixed for the lifetime of object.
There are many good reasons for this: Immutable classes are easier to design, implement and use than mutable classes. They are less prone to error and are more secure.
To make class immutable:
  1. Don't provide any methods that modify the object's state 
  2. Ensure that theclass can't be extended.
  3. Make all fields final.
  4. Make all fields private.
Here is a good sample of immutable class, Notice how the aritmetic operations create and return a new Complex instance rather than modifying this instance.

  • Immutable objects are simple, an immutable object can be in exactly one state, the state in which it was created.
  • Immutable ojects are inherently thread-safe; they require no synchronization
  • Immutable ojects can be shared freely. One easy way to do this is to rpvoide public static final constants for frequently used values, for example
public static final Complex ZERO = new Complex(0, 0);
public static final Complex ONE = new Complex(1, 0);
public static final Complex I = new Complex(0, 1); 
 To summarize, resist the urge to write a setter method for every getter method. Classes should be immutable unless there's a very good reason to make them mutable.

No comments: