principleModeratepending
Principle: Immutability by default
Viewed 0 times
immutabilityfrozenreadonlyfunctionalpure functionsside effects
Problem
Mutable state causes hard-to-track bugs: race conditions, unexpected side effects, and difficulty reasoning about code.
Solution
Prefer immutable data unless mutation is specifically needed:
Where mutation IS appropriate:
Immutability benefits:
# Python: use frozen dataclasses, tuples, frozensets
from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
x: float
y: float
def translate(self, dx, dy) -> 'Point':
return Point(self.x + dx, self.y + dy) # New object// TypeScript: use Readonly, as const
type Config = Readonly<{
host: string;
port: number;
}>;
// as const for literal types
const COLORS = ['red', 'blue', 'green'] as const;
// type: readonly ['red', 'blue', 'green']
// Spread for immutable updates
const updated = { ...user, name: 'Alice' };
const newItems = [...items, newItem];
const filtered = items.filter(x => x.active);// Rust: immutable by default
let x = 5; // Immutable
let mut y = 5; // Explicitly mutableWhere mutation IS appropriate:
- Performance-critical inner loops
- Builder pattern during construction
- Local variables that never escape their scope
- Data structures where copying is prohibitively expensive
Immutability benefits:
- Thread-safe without locks
- No defensive copying needed
- Easier to test (no setup/teardown state)
- Time-travel debugging possible
Why
Most bugs come from unexpected state changes. Immutability eliminates this class of bugs entirely and makes code easier to reason about.
Context
Code design decisions about mutability
Revisions (0)
No revisions yet.