Immutability: why so many languages and frameworks push it
An immutable value can't be changed after it's created. Instead of modifying it, you create a new value with the changes. Many modern languages, libraries and UI frameworks encourage this style.
Why immutability helps
- Fewer surprises: if a function receives data it can't change, you don't have to worry about it being modified somewhere else.
- Easier reasoning: values mean the same thing everywhere they appear.
- Safer concurrency: data that never changes can be shared between threads without locks.
- Cheap change detection: UI frameworks can check whether something changed by comparing references instead of deep-comparing objects.
- Undo and history: keeping previous versions is easy when old values are never overwritten.
Costs and caveats
- Copying overhead: creating new objects can cost memory and time. Persistent data structures reduce this by sharing unchanged parts.
- Awkward syntax in languages not designed for it; deeply nested updates can be verbose.
- Shallow vs deep: "freezing" an object in some languages only protects the top level.
- Real programs need state. Immutability usually means controlling where change happens, not eliminating it.
Practical middle ground
- Make data immutable by default and allow mutation in small, contained places.
- Prefer
const,final,valor read-only types where your language offers them. - Avoid mutating function arguments.
Do you default to immutable data in your codebase? Where has it saved you from a bug, or where did it get in the way?
Comments · 4
The "why" that worked for me: if nothing can change a value behind your back, bugs from shared state mostly disappear. It makes code easier to reason about.
It also makes change detection cheap for UI frameworks, since a new object reference tells you something changed. That's a real performance and simplicity win.
Doesn't copying data every time hurt performance? How do big apps avoid that?
Persistent data structures share unchanged parts between versions, so a "copy" only builds the changed branch. Libraries like Immer and languages like Clojure do this.