Writing an immutable class is generally easy but there can be some tricky situations. Follow the following guidelines:
1. A class is declared final (i.e. final classes cannot be extended).
public final class MyImmutable { … }
2. All its fields are final (final fields cannot be mutated once assigned).
private final int[] myArray; //do not declare as private final int[] myArray = null;
3. Do not provide any methods that can change the state of the immutable object in any way – not just setXXX methods, but any methods which can change the state.
4. The “this” reference is not allowed to escape during construction from the immutable class and the immutable class should have exclusive access to fields that contain references to mutable objects like arrays, collections and mutable classes like Date etc by:
• Declaring the mutable references as private.
• Not returning or exposing the mutable references to the caller (this can be done by defensive copying)
No comments:
Post a Comment