Files
2nd/10_Wiki/Topics/Architecture/불변성(Immutability).md
T
koriweb d8a80f6272 chore(wiki): dangling 링크 canonical 정규화 (768파일/1200건)
이름만 다른(표기 변형) [[위키링크]]를 대상 문서의 canonical 제목으로 치환해
끊겼던 1,200개 링크를 연결. 제목/파일명 정규화 일치만 적용하고 별칭 매칭은
과병합 위험으로 제외(애매성 가드). 원본은 _link_reconcile_backup/ 에 백업.
도구: Datacollect/scripts/link_reconcile_apply.mjs

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-08 12:24:15 +09:00

158 lines
5.3 KiB
Markdown

---
id: wiki-2026-0508-불변성-immutability
title: 불변성 (Immutability)
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [Immutability, Immutable Data, Persistent Data Structures, 불변 자료구조]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
verification_status: applied
tags: [functional-programming, concurrency, data-structures, design]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: multi
framework: Immer/Immutable.js
---
# 불변성 (Immutability)
## 매 한 줄
> **"매 생성 후 의 state 의 mutate 의 X — 매 update 의 new value 의 produce."**. 매 shared mutable state 의 concurrency · reasoning · debugging hell 의 root cause — 매 immutable data 의 매 reasoning 의 local 의 keep · race 의 eliminate · 매 time-travel · undo 의 cheap. 2026 modern stack (Rust ownership, Clojure, Immer, structural sharing) 은 매 immutability 의 performance cost 의 near-zero.
## 매 핵심
### 매 levels
- **Reference immutable**: 매 variable rebind X (`const x = ...`).
- **Shallow immutable**: 매 object reference X 의 change, 매 nested mutable 가능.
- **Deep immutable**: 매 entire tree mutable X (Object.freeze 매 recursive).
- **Persistent**: 매 update 의 structural sharing 의 통한 efficient (HAMT, finger tree).
### 매 benefits
- **Concurrency**: 매 lock-free read · 매 race 의 X.
- **Equality**: 매 reference equality 의 enough — `prev === next` (React memo).
- **Time-travel**: 매 undo/redo · 매 debugging snapshot.
- **Predictability**: 매 function 의 input 의 mutate X — 매 reason 의 local.
### 매 응용
1. 매 React/Redux state — 매 immutable update 의 re-render 의 cheap detect.
2. 매 Event sourcing — 매 event log immutable.
3. 매 functional core, imperative shell pattern.
## 💻 패턴
### JavaScript — Object spread (shallow)
```javascript
const user = { name: "Ada", age: 30 };
const older = { ...user, age: 31 }; // user 의 unchanged
```
### Immer — mutable syntax, immutable result
```javascript
import { produce } from "immer";
const next = produce(state, draft => {
draft.users[0].name = "Ada"; // 매 draft 의 freely mutate
draft.todos.push({ text: "x" });
});
// next 매 new immutable, state 매 unchanged
```
### Rust — ownership + immutable by default
```rust
let v = vec![1, 2, 3]; // immutable
let mut w = v.clone(); // explicit mut
w.push(4);
// fn 매 borrow as &T 의 read-only access
fn sum(xs: &[i32]) -> i32 { xs.iter().sum() }
```
### Clojure — persistent data structures
```clojure
(def m {:a 1 :b 2})
(def m2 (assoc m :c 3)) ; 매 m unchanged, structural sharing
(= (get m :c) nil) ; true
```
### Python — frozen dataclass
```python
from dataclasses import dataclass, replace
@dataclass(frozen=True)
class User:
id: int
name: str
u1 = User(1, "Ada")
u2 = replace(u1, name="Grace") # 매 new instance
```
### Immutable.js (Map / List)
```javascript
import { Map } from "immutable";
const m = Map({ a: 1, b: 2 });
const m2 = m.set("c", 3); // structural sharing
```
### Event sourcing — append-only
```typescript
interface Event { type: string; payload: any; ts: number; }
class Aggregate {
private events: readonly Event[] = [];
apply(e: Event) { return new Aggregate([...this.events, e]); }
state() { return this.events.reduce(reducer, initial); }
}
```
### React — useState 의 immutable update
```typescript
const [todos, setTodos] = useState<Todo[]>([]);
// add
setTodos(prev => [...prev, newTodo]);
// update by id
setTodos(prev => prev.map(t => t.id === id ? { ...t, done: true } : t));
// remove
setTodos(prev => prev.filter(t => t.id !== id));
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| 매 React/Redux state | Immer or spread |
| 매 hot path mutation (10M+/s) | Mutable + 매 boundary 에서 freeze |
| 매 deeply nested update | Immer (productivity > raw perf) |
| 매 multi-thread shared | Persistent + lock-free read |
| 매 audit/compliance | Event sourcing — append-only log |
**기본값**: 매 default immutable, 매 measured hotspot 의 mutable optimize.
## 🔗 Graph
- 부모: [[Functional_Programming]]
- 변형: [[Persistent_Data_Structures]]
- 응용: [[Event Sourcing Pattern|Event_Sourcing]] · [[프론트엔드 및 UIUX 표준|Redux]]
- Adjacent: [[Referential_Transparency]] · [[Concurrency]]
## 🤖 LLM 활용
**언제**: 매 mutation bug 의 hunt — 매 trace where state 의 escape, 매 immutable refactor 의 propose.
**언제 X**: 매 raw numeric kernel · 매 GPU buffer — 매 in-place 의 unavoidable.
## ❌ 안티패턴
- **Shallow freeze**: `Object.freeze(x)` 매 nested 의 still mutable — 매 deep freeze 의 필요.
- **Mutating in reducer**: Redux `state.x = 1` — 매 silent bug, 매 detect 의 hard.
- **Copy 의 매 op**: 매 deep clone 매 every update — 매 structural sharing 의 use.
- **Frozen 의 mutate 의 try**: strict mode 매 throw — 매 silent fail 의 X.
- **Immutable 의 cargo cult**: 매 single-threaded local var 의 over-immutable — 매 noise.
## 🧪 검증 / 중복
- Verified (Okasaki *Purely Functional Data Structures*; Immer docs; Rust Book ch4).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — levels, persistent structures, language patterns |