[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -1,93 +1,200 @@
|
||||
---
|
||||
id: wiki-2026-0508-parse-dont-validate
|
||||
title: Parse dont validate
|
||||
title: Parse, Don't Validate
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-D95ED1]
|
||||
aliases: [parse don't validate, type-driven design, smart constructor, refinement type]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
tags: [auto-reinforced]
|
||||
confidence_score: 0.95
|
||||
verification_status: applied
|
||||
tags: [type-system, design, haskell, typescript, validation]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
github_commit: "[P-Reinforce] Continuous Worker - Parse dont validate"
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: TypeScript/Haskell
|
||||
framework: Zod, Effect, Brand types
|
||||
---
|
||||
|
||||
# [[Parse dont validate|Parse dont validate]]
|
||||
# Parse, Don't Validate
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> 'Parse, don't validate(검증하지 말고 파싱하라)'는 프로그램의 경계에서 타입이 없거나 느슨한 데이터를 잘 정의된 타입의 데이터로 변환하는 소프트웨어 설계 철학입니다[1]. 코드 전반에 걸쳐 데이터의 유효성을 반복적으로 검사하는 대신, 시스템 진입점에서 단 한 번 파싱하여 안전한 타입으로 만듭니다[1]. 이를 통해 유효성 검사 로직의 파편화를 막고 타입 검사기의 정적 분석 능력을 극대화하여 코드의 예측 가능성과 안정성을 높입니다[2, 3].
|
||||
## 매 한 줄
|
||||
> **"매 unsafe input 매 한번 parse → 매 typed value 매 produce, 매 downstream 매 다시 검증 의 X"**. 매 2019 Alexis King (lexi-lambda) 의 Haskell post 의 origin. 매 핵심 idea: 매 validation 매 boolean 의 throw — 매 information 의 lose. 매 parsing 매 validated 형식 의 새 type 의 produce — 매 type system 의 매 invariant 의 carry.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **기본 원칙 및 파싱 흐름**: Alexis King의 동명 아티클을 통해 널리 알려진 이 개념은 시스템의 경계(입구 및 출구)에서 입력 데이터를 한 번 파싱하는 것을 핵심으로 합니다[1, 2]. 이 파싱 단계에서 데이터의 유효성 검사와 변환이 동시에 이루어지며, 이후의 애플리케이션 흐름에서는 완전히 타입이 지정되고 검증된 데이터만을 사용하게 됩니다[1].
|
||||
- **수비적 프로그래밍(Defensive Programming)의 정점**: 단순히 데이터의 유효성 여부만 확인(Validate)하고 끝내는 것이 아니라, 데이터를 더 구체적이고 신뢰할 수 있는 타입의 객체로 변환(Parse)하여 시스템 내부로 전달합니다[3]. 이는 의도하지 않은 불확실한 데이터의 유입을 원천적으로 차단하는 견고한 아키텍처적 방어막 역할을 합니다[3].
|
||||
- **제어 흐름(Control flow)과 개발자 경험 향상**: 유효성 검사 로직을 시스템 경계에만 배치함으로써, 비즈니스 로직 곳곳에 검증 코드가 어지럽게 흩어지는 것을 방지할 수 있습니다[2]. 결과적으로 타입 시스템의 정적 분석에 무거운 작업을 위임하여 개발자의 신뢰를 높이고, 관리해야 할 코드의 양(Code volume)과 복잡도를 줄이는 데 크게 기여합니다[2, 4].
|
||||
- **구현 방법 및 생태계 도구**: 이 철학을 실현하기 위해 Zod와 같은 런타임 유효성 검사/파싱 라이브러리가 자주 활용됩니다[3, 5]. 구체적으로는 Zod 등을 통해 알 수 없는(Unknown) 데이터를 잘 알려진 타입으로 변환하며, 런타임 데이터에 Branded Types를 부여하여 시스템 내부로 전달하는 것이 이 철학을 완벽히 실현하는 구체적 방법론입니다[3, 5].
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
|
||||
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
|
||||
### 매 validate 의 problem
|
||||
```ts
|
||||
// 매 anti-pattern
|
||||
function isNonEmpty<T>(arr: T[]): boolean { return arr.length > 0; }
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- **Related Topics:** Branded Types, [[Zod|Zod]], Defensive Programming, Static Analysis, [[Structural Typing|Structural Typing]]
|
||||
- **Projects/Contexts:** API Boundary Handling, [[State|State]] [[Management|Management]]
|
||||
- **Contradictions/Notes:** 소스 내에서 이 철학에 대한 상반된 주장이나 모순은 발견되지 않습니다. 오히려 상태 관리(State management) 문제나 복잡성 증가를 완화하는 TypeScript의 핵심 모범 사례 중 하나로 강력히 권장됩니다[1, 6].
|
||||
function head<T>(arr: T[]): T {
|
||||
if (!isNonEmpty(arr)) throw new Error("empty!");
|
||||
return arr[0]; // 매 type system 매 still T | undefined
|
||||
}
|
||||
```
|
||||
- 매 `isNonEmpty` check 후 매 type 매 `T[]` (그대로) — 매 information lost.
|
||||
- 매 head 매 매번 다시 check or throw.
|
||||
- 매 caller 매 invariant 의 untracked.
|
||||
|
||||
---
|
||||
*Last updated: 2026-04-18*
|
||||
### 매 parse 의 solution
|
||||
```ts
|
||||
type NonEmpty<T> = readonly [T, ...T[]];
|
||||
|
||||
---
|
||||
function parseNonEmpty<T>(arr: T[]): NonEmpty<T> | null {
|
||||
return arr.length > 0 ? (arr as NonEmpty<T>) : null;
|
||||
}
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
function head<T>(arr: NonEmpty<T>): T {
|
||||
return arr[0]; // 매 항상 safe — type system 의 guarantee
|
||||
}
|
||||
```
|
||||
- 매 parse 결과 매 새 type — 매 invariant 가 매 type 에 baked in.
|
||||
- 매 downstream 매 trust — 매 re-check 의 X.
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
### 매 응용
|
||||
1. API request body validation (Zod / Effect Schema).
|
||||
2. ID type discrimination (UserId vs OrderId).
|
||||
3. URL / Email parsing.
|
||||
4. Smart constructor (private constructor + parse function).
|
||||
5. Domain modeling (PositiveNumber, NonEmptyString).
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
## 💻 패턴
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
### 1. Branded type (TypeScript)
|
||||
```ts
|
||||
type Brand<T, B> = T & { readonly __brand: B };
|
||||
type Email = Brand<string, 'Email'>;
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
function parseEmail(s: string): Email | null {
|
||||
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s) ? (s as Email) : null;
|
||||
}
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
function sendMail(to: Email, body: string) { /* 매 trust to */ }
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
const raw = "user@example.com";
|
||||
const email = parseEmail(raw);
|
||||
if (!email) throw new Error("bad email");
|
||||
sendMail(email, "hi"); // 매 OK
|
||||
sendMail(raw, "hi"); // 매 type error
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### 2. Zod schema (parse-style)
|
||||
```ts
|
||||
import { z } from 'zod';
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
const UserSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
email: z.string().email(),
|
||||
age: z.number().int().min(0).max(150),
|
||||
});
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
type User = z.infer<typeof UserSchema>; // 매 fully-typed
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
app.post('/users', (req, res) => {
|
||||
const result = UserSchema.safeParse(req.body);
|
||||
if (!result.success) return res.status(400).json(result.error);
|
||||
createUser(result.data); // 매 trust — User type 매 guaranteed
|
||||
});
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### 3. Effect Schema (2026 의 매 modern)
|
||||
```ts
|
||||
import { Schema as S } from "effect";
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
const PositiveInt = S.Int.pipe(S.positive(), S.brand("PositiveInt"));
|
||||
type PositiveInt = S.Schema.Type<typeof PositiveInt>;
|
||||
|
||||
const decode = S.decodeUnknownSync(PositiveInt);
|
||||
const x = decode(42); // 매 PositiveInt
|
||||
const y = decode(-1); // 매 throws ParseError
|
||||
```
|
||||
|
||||
### 4. Smart constructor (Haskell-style)
|
||||
```ts
|
||||
class NonEmptyList<T> {
|
||||
private constructor(public readonly items: readonly T[]) {}
|
||||
|
||||
static parse<T>(items: readonly T[]): NonEmptyList<T> | null {
|
||||
return items.length > 0 ? new NonEmptyList(items) : null;
|
||||
}
|
||||
|
||||
get head(): T { return this.items[0]; } // 매 always safe
|
||||
get tail(): readonly T[] { return this.items.slice(1); }
|
||||
}
|
||||
```
|
||||
|
||||
### 5. Discriminated ID type
|
||||
```ts
|
||||
type UserId = Brand<string, 'UserId'>;
|
||||
type OrderId = Brand<string, 'OrderId'>;
|
||||
|
||||
function getUser(id: UserId): User { /*...*/ }
|
||||
function getOrder(id: OrderId): Order { /*...*/ }
|
||||
|
||||
const uid = parseUserId(req.params.id);
|
||||
if (!uid) throw new Error();
|
||||
getUser(uid); // 매 OK
|
||||
getOrder(uid); // 매 type error 매 prevent mix-up
|
||||
```
|
||||
|
||||
### 6. Parse at boundary, trust within
|
||||
```ts
|
||||
// 매 boundary (HTTP / DB / file IO)
|
||||
const userOrErr = UserSchema.safeParse(rawJson);
|
||||
|
||||
// 매 internal — User type 매 항상 valid
|
||||
function processUser(u: User) {
|
||||
// 매 u.email 매 valid email — 매 re-check 의 X
|
||||
// 매 u.age 매 0-150 매 — 매 re-check 의 X
|
||||
}
|
||||
```
|
||||
|
||||
### 7. Refinement chain
|
||||
```ts
|
||||
const NonEmptyString = z.string().min(1).brand<'NonEmptyString'>();
|
||||
const EmailString = NonEmptyString.refine(
|
||||
s => /^[^@]+@[^@]+$/.test(s)
|
||||
).brand<'Email'>();
|
||||
type Email = z.infer<typeof EmailString>;
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Apply parse-don't-validate? |
|
||||
|---|---|
|
||||
| Trust boundary (HTTP / DB / file) | Yes — 매 must |
|
||||
| ID across multiple types | Yes — 매 brand to prevent mix |
|
||||
| Hot path internal-only | Optional — perf trade-off |
|
||||
| Quick script / prototype | Skip — overhead > value |
|
||||
| Domain primitive (Money, Date) | Yes — 매 invariant carrying |
|
||||
|
||||
**기본값**: 매 boundary 의 매 Zod (or Effect Schema) parse + 매 internal 의 매 inferred type 으로 trust.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Type-Driven Design]] · [[Domain Modeling]]
|
||||
- 변형: [[Refinement Type]] · [[Dependent Type]] · [[Smart Constructor]]
|
||||
- 응용: [[Zod]] · [[Effect Schema]] · [[Branded Type]] · [[ADT (Algebraic Data Type)]]
|
||||
- Adjacent: [[Validation]] · [[Type Narrowing]] · [[Make Illegal States Unrepresentable]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 API server / public library 의 매 input validation. 매 ID mix-up bug 매 routine 한 codebase. 매 domain rule 매 type-encode 가능 한 경우.
|
||||
**언제 X**: 매 internal-only quick script. 매 highly dynamic JSON 의 schema 가 unknown. 매 perf-critical hot loop (parse overhead).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Validate 후 raw type 의 pass**: 매 invariant 매 lose. 매 항상 새 type 의 return.
|
||||
- **Parse 매 boundary X 의 매 매 layer 의 repeat**: 매 perf 손실 + 매 동일 logic 의 duplicate.
|
||||
- **Brand 의 매 runtime check 의 X**: 매 cast 매 type-only — 매 parse function 매 항상 runtime check 포함.
|
||||
- **Optional 의 abuse**: 매 `email?: string` — 매 invariant 매 unclear. 매 명확한 `Email | null`.
|
||||
- **Throw on parse fail (preference)**: 매 Result type / safeParse 의 매 prefer — 매 caller flow 매 explicit.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Alexis King "Parse, Don't Validate" 2019, Zod 4 / Effect 3.x docs 2026-05).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — Branded types + Zod/Effect Schema 의 modern parse pattern |
|
||||
|
||||
Reference in New Issue
Block a user