Immutability
Immutability means data cannot change after creation, so updates produce new values, making code easier to reason about and safe to share across threads.
Immutability is the property that, once a value or object is created, it cannot be modified. Any operation that appears to change immutable data instead returns a new value, leaving the original untouched. Immutability is a foundational idea in functional programming and increasingly common in mainstream code.
How It Works
With mutable data, code can alter an object in place, and any reference to that object sees the change. With immutable data, you create a modified copy and leave the original intact. Languages support this through immutable types (strings in Java and Python, records, frozen collections) and through persistent data structures that share unchanged parts between versions for efficiency, avoiding wholesale copying. Practices like const/final declarations and value objects reinforce immutability.
Why It Matters
Immutable data is easier to reason about because a value never changes out from under you. This is especially valuable in concurrent and parallel code: immutable data can be shared across threads with no locks and no risk of data races, eliminating a whole class of bugs. Immutability also makes change tracking, caching, undo, and time-travel debugging straightforward, and it underpins patterns like event sourcing, where recorded facts are never altered.
The trade-off is potential overhead from creating new objects, though persistent structures and modern runtimes greatly reduce it. The clarity and safety usually outweigh the cost.
Related Terms
A pure function combines immutability with no side effects. Concurrency and parallelism benefit directly from immutable data. Event sourcing stores immutable events.