Make Objects Immutable
An immutable object is an object whose state cannot be modified after it is created.
Integer are examples
of immutable objects from the JDK.
As outlined in Effective Java by Joshua Bloch:
Classes should be immutable unless there's a very good reason to make them mutable....If a class cannot be made immutable, limit its mutability as much as possible.
There are a number of advantages to making a class immutable:
- Inherently thread-safe, and can be shared freely without the need for synchronization
- Inherently safe from aliasing
- Inherently safe from side effects
- Require no setter implementations or
- Can be used as keys in a
HashSet, as they will not change
- The validity of any fields only needs to be checked once
- Failure atomicity - if an object fails to be created/an exception is thrown, it will remain in a consistent state
Doing the Dirty
To make a class immutable, you must:
- Ensure the class cannot be overridden, by making it
finalor by using static factories with a private constructor
- Make all fields
- Do not provide any setter methods, or methods that can alter the state of the object
- Do not allow referenced mutable objects within the object to be modified or accessed directly
- Prevent methods from being overridden
- If the class has a superclass, make sure it is also immutable