[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
@@ -2,98 +2,149 @@
id: wiki-2026-0508-primitive-obsession-기본-타입-집착
title: Primitive Obsession (기본 타입 집착)
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [Primitive Obsession, 기본 타입 집착, stringly-typed]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
confidence_score: 0.9
verification_status: applied
tags: [refactoring, code-smell, type-system, ddd]
raw_sources: []
last_reinforced: 2026-05-08
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: python-typescript-rust
framework: refactoring
---
# [[Primitive Obsession (기본 타입 집착)]]
# Primitive Obsession (기본 타입 집착)
## 📌 한 줄 통찰 (The Karpathy Summary)
기본 타입 집착(Primitive Obsession)개발자가 간단한 작업을 위해 전용 객체를 생성하는 대신 숫자나 문자열과 같은 기본 데이터 타입(Primitive Type)만을 과도하게 사용하는 코드 스멜(Code Smell)입니다 [1, 2]. 이는 코드를 비대하게 만드는 '비대화(Bloaters)' 유형의 문제로 분류되며, 시스템에 의미 있는 추상화가 누락되어 코드 중복과 복잡성을 유발합니다 [3, 4]. 결과적으로 단일 책임 원칙(SRP)을 위반하게 만들어 코드 수정 시 예상치 못한 부수 효과(Side Effect)를 발생시킬 위험을 높입니다 [4].
## 한 줄
> **"매 string/int이 매 domain concept를 매 가장한다"**. Primitive Obsession은 매 `UserId`, `Email`, `Money` 같은 매 domain concept를 매 raw `str`/`int`로 매 표현해 매 type system이 매 invariant 보장 못 하는 매 code smell. Fowler "Refactoring" (1999, 2nd ed. 2018) 의 매 classic smell — 매 modern fix는 매 newtype / value object.
## 📖 구조화된 지식 (Synthesized Content)
* **발생 원인과 증상:**
객체 지향 프로그래밍에 익숙하지 않은 개발자들은 금액(숫자와 통화의 결합), 범위(상한선과 하한선), 전화번호, 우편번호 등의 작은 개념에 대해 새로운 클래스를 만드는 것을 꺼리는 경향이 있습니다 [2]. 그 결과 풍부한 개념(Richer concepts)이 도입되지 못하고 단순 데이터에 기반한 조건 분기문이 많아지며, 의미가 결여된 기본 타입들이 코드 전반에 흩어지게 됩니다 [3, 5].
* **구조적 악영향:**
기본 타입 집착은 코드가 너무 커져서 한눈에 파악하기 어렵게 만드는 '비대화(Bloaters)' 스멜로 분류됩니다 [4, 6]. 기본 타입에만 의존하면 누락된 추상화로 인해 코드가 중복되고, 수정 시 여러 곳을 건드려야 하므로 유지보수가 힘들어집니다 [3].
* **해결을 위한 리팩토링 기법:**
* **데이터 값을 객체로 바꾸기 (Replace Data Value/Primitive with Object):** 개별적인 데이터 값을 전용 객체로 변환하여 기본 타입의 한계를 벗어납니다 [2, 3].
* **타입 코드를 클래스/서브클래스/상태·전략으로 바꾸기:** 기본 타입이 타입 코드(Type Code)로 사용될 때, 동작에 영향을 주지 않는다면 클래스로(Replace Type Code with Class) 바꿉니다. 만약 조건문에 영향을 준다면 서브클래스나 상태/전략 패턴으로(Replace Type Code with Subclasses or State/Strategy) 변경하며, 관련 조건식은 다형성으로(Replace Conditional with Polymorphism) 교체합니다 [2, 3].
* **클래스 추출하기 (Extract Class):** 함께 다녀야 할 기본 타입 필드들이 논리적인 그룹을 이루고 있다면 별도의 클래스로 추출합니다 [3, 7].
* **매개변수 객체 만들기 (Introduce Parameter Object):** 매개변수 목록에 기본 타입들이 길게 나열되어 있다면 이를 하나의 객체로 묶습니다 [3, 7].
* **배열을 객체로 바꾸기 (Replace Array with Object):** 배열 내의 기본 타입 요소들을 특정 의미로 분해해서 사용하고 있다면 명확한 객체로 변환합니다 [7].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
* **레코드 및 객체 생성의 오버헤드:** 기본 타입을 객체나 레코드 타입으로 대체하면 구조적 오버헤드(Overhead)가 발생할 수 있습니다. 예를 들어, 데이터베이스의 추가적인 테이블 생성을 의미할 수도 있고, 단지 한두 개의 단순한 작업을 위해 새로운 객체 구조를 생성하는 것이 번거롭게 느껴질 수 있습니다 [1]. 이것이 많은 개발자가 객체지향의 이점을 누리지 못하고 기본 타입에 집착하게 만드는 주된 진입 장벽입니다 [1, 2].
* **적절한 추상화 도출의 필요성:** 기본 타입을 무작정 객체로 바꾸는 것만이 능사는 아니며, 코드베이스에 충분한 로직이 쌓였을 때 누락된 추상화(Missing abstractions)를 정확히 찾아내야 합니다. 이를 통해 중복을 제거하고 코드를 단순화하는 올바른 방향으로 개념이 도입되어야 리팩토링의 효과를 거둘 수 있습니다 [3].
### 매 증상
- **매 String 폭주**: 매 `email: str`, `phone: str`, `country_code: str` 매 swap 가능.
- **매 Magic numbers**: 매 `status: int = 3` 매 의미 불명.
- **매 Validation duplication**: 매 every callsite마다 매 `if "@" in email`.
- **매 Type confusion**: 매 `transfer(from_id, to_id)` 매 인자 swap 매 컴파일러 못 잡음.
---
*Last updated: 2026-05-03*
### 매 Fix 전략
- **매 Newtype**: Rust `struct UserId(u64);`.
- **매 Value Object**: DDD 의 매 `Email`, `Money` immutable class.
- **매 Branded type**: TypeScript `type UserId = string & { __brand: "UserId" }`.
- **매 NewType pattern**: Python `typing.NewType("UserId", int)`.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Domain modeling (DDD) — Bounded context의 매 first-class concept.
2. Money handling (currency + amount tied).
3. Identifier safety (UserId vs OrderId mix-up 방지).
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Python NewType + dataclass
```python
from typing import NewType
from dataclasses import dataclass
from decimal import Decimal
## 🧪 검증 상태 (Validation)
UserId = NewType("UserId", int)
OrderId = NewType("OrderId", int)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
@dataclass(frozen=True)
class Money:
amount: Decimal
currency: str
def __post_init__(self):
if self.amount < 0: raise ValueError("negative")
if len(self.currency) != 3: raise ValueError("ISO-4217")
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🔗 지식 연결 (Graph)
- **Parent:** [[10_Wiki/Topics]]
- **Related:** *(TODO: 최소 2개)*
- **Opposite / Trade-off:** *(TODO)*
- **Raw Source:** 직접 입력
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
def transfer(src: UserId, dst: UserId, m: Money): ...
# transfer(OrderId(1), UserId(2), Money(...)) # 매 mypy error
```
## 🤔 의사결정 기준 (Decision Criteria)
### Rust newtype
```rust
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct UserId(u64);
**선택 A를 써야 할 때:**
- *(TODO)*
#[derive(Debug, Clone, Copy)]
pub struct OrderId(u64);
**선택 B를 써야 할 때:**
- *(TODO)*
fn fetch_user(id: UserId) { /* ... */ }
// fetch_user(OrderId(7)); // 매 compile error
```
**기본값:**
> *(TODO)*
### TypeScript branded types
```typescript
type Brand<T, B> = T & { readonly __brand: B };
type Email = Brand<string, "Email">;
type UserId = Brand<number, "UserId">;
## ❌ 안티패턴 (Anti-Patterns)
function parseEmail(s: string): Email {
if (!/^[^@]+@[^@]+$/.test(s)) throw new Error("invalid");
return s as Email;
}
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Value object with invariant
```python
@dataclass(frozen=True)
class Email:
value: str
def __post_init__(self):
if "@" not in self.value: raise ValueError("invalid email")
object.__setattr__(self, "value", self.value.lower())
```
### Refactor: Replace Type Code with Subclass
```python
# Before — magic int status
class Order:
status: int # 0=pending, 1=paid, 2=shipped
# After — sealed states
class OrderStatus: pass
class Pending(OrderStatus): pass
class Paid(OrderStatus): pass
class Shipped(OrderStatus):
tracking: str
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Domain identifier | Newtype |
| Domain value (Money, Email) | Value Object |
| 매 enum-like int code | Sealed subclass / Enum |
| Throwaway script | 매 raw primitive OK |
**기본값**: Newtype for IDs, Value Object for domain values.
## 🔗 Graph
- 부모: [[Code-Smell]] · [[Refactoring]]
- 변형: [[Newtype-Pattern]] · [[Value-Object]] · [[Branded-Types]]
- 응용: [[DDD]] · [[Type-Safety]]
- Adjacent: [[Stringly-Typed]] · [[Magic-Numbers]] · [[Replace-Type-Code]]
## 🤖 LLM 활용
**언제**: domain model 설계, 매 API boundary type 선택, 매 refactoring 제안.
**언제 X**: 매 1-time script.
## ❌ 안티패턴
- **매 Stringly-typed everything**: 매 모든 domain concept를 매 str.
- **매 Validation lazy**: 매 boundary 통과 후 매 raw str 그대로 흘림.
- **매 Tuple as struct**: 매 `(int, str, bool)` 매 의미 모름.
- **매 매 시점 validation**: 매 매번 caller가 매 validate 수행.
## 🧪 검증 / 중복
- Verified (Fowler "Refactoring" 2nd ed. 2018, Evans "DDD" 2003).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — newtype/value-object patterns + refactoring guide |