Immutability
In Object Orientation, an object is considered to be Immutable if its state cannot be modified once it has been created. As much as possible, ensure objects are Immutable.
This is also sometimes simplified to as “Don’t use setters”.
Rationale
Objects that are immutable are…
- Easier to test
- Thread/Concurrency safe
- Void of side effects (i.e. execution will produce the same result each time)
- Easier to cache
- (possibly) safe to put in a Set or use as a key in a Map/Hash/Dictionary
Implications
- Objects are only immmutable if there is no way to modify any of their properties after the object’s construction. Primitive types such as
int,Stringare usually immutable but custom types and collections may not be. - Developers need to understand how immutablility is ensured in specific languages.
Examples
Example of mutable
|
|
Example of immutable
|
|