About
A state who is immutable cannot be changed.
An variable (object) is considered immutable if its state cannot change after it is constructed.
Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be:
- corrupted by thread interference
- or observed in an inconsistent state.
Rules
- Don't provide “setter” methods — methods that modify fields or objects referred to by fields.
- Make all fields final and private (ie have a local scope)
- …
Immutable objects are great. But sometimes refactoring an existing class to be immutable is really hard because code design implies that you need to publish an object before filling it completely. Still, you can improve your code.