Immutability
medium 45 minAn immutable object keeps the value it was born with.
Watch lesson4:40
Where it shows up
The same pattern appears across everyday software.
Java String
The documentation says that strings are constant and that, because they are immutable, they can be shared. Literals are interned for that reason.
java.time
`LocalDate`, `Instant` and `Duration` are documented as immutable and thread safe. They replaced `Date`, which has setters. `plusDays` returns a new date.
Java records
JEP 395 (Java 16) describes records as shallowly immutable carriers of data: final fields, but a list inside stays a list.
Python tuple and frozenset
Immutable sequences and sets can be dictionary keys when their elements can be hashed. The documentation notes that joining immutable sequences always makes a new object.
Clojure collections
All are immutable and persistent. The reference says that modified versions use structural sharing.
Redux
The style guide marks not mutating state as essential. A reducer returns a new state object, so a change is seen by comparing references.
Git objects
A commit is stored under the hash of its content. Amending does not edit the commit, it creates another one with another hash, and moves the branch to it.
Kubernetes ConfigMaps
A ConfigMap can be marked `immutable: true`. It then cannot be edited, only deleted and created again. The documentation names protection from accidental updates and less load from watching.
Amazon S3 Object Lock
Stores objects in a write once, read many model: a protected version cannot be overwritten or deleted during its retention time.
CopyOnWriteArrayList
Each change makes a fresh copy of the array, so readers iterate over a snapshot without locks. The documentation warns that it fits when reading far outnumbers writing.