- Don't provide "setter" methods - methods that modify fields or objects referred to by fields.
- Make all fields final and private. Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.
- If the instance fields include references to mutable objects, don't allow those objects to be changed
- Don't provide methods that modify the mutable objects.
- Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.
- The constructor uses clone() to create a distinct copy of the parameter array. If the caller of the constructor subsequent changed the parameter array, it would not affect the state of the ImmutableIntArray.
- The getValue() method also uses clone() to create the array that is returned. If the caller were to change the result array, it would not affect the state of the ImmutableIntArray.
- All properties must be set in the constructor(s) or factory method(s).There should be no setters.
- If it is necessary to include setters for interface compatibility reasons, they should either do nothing or throw an exception.
- All properties should be declared as private and final.
- For all properties that are references to mutable types:
- the property should be initialized with a deep copy of the value passed via the constructor
- the property's getter should return a deep copy of the property value.
- The class should be declared as final to prevent someone creating a mutable subclass of an immutable class.
- Immutability does not prevent object from being nullable; e.g. null can be assigned to a String variable.
- If an immutable classes properties are declared as final, instances are inherently thread-safe. This makes immutable classes a good building block for implementing multi-threaded applications.
Nice one
ReplyDelete