[G1-Sync] Manual knowledge update
This commit is contained in:
+177
-73
@@ -2,100 +2,204 @@
|
||||
id: wiki-2026-0508-replace-conditional-with-polymor
|
||||
title: Replace Conditional with Polymorphism (조건식을 다형성으로 바꾸기)
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: []
|
||||
aliases: [Replace Conditional with Polymorphism, RCwP, Polymorphism Refactoring]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.92
|
||||
tags: [uncategorized]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [refactoring, oop, design-pattern, fowler]
|
||||
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: TypeScript
|
||||
framework: none
|
||||
---
|
||||
|
||||
# [[Replace Conditional with Polymorphism (조건식을 다형성으로 바꾸기)]]
|
||||
# Replace Conditional with Polymorphism (조건식을 다형성으로 바꾸기)
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
Replace Conditional with Polymorphism(조건식을 다형성으로 바꾸기)는 객체의 타입에 따라 다르게 동작하는 복잡한 조건문(switch 또는 if-then-else 등)을 객체 지향의 다형성을 활용하여 해결하는 구조적 리팩토링 기법이다 [1, 2]. 조건문의 각 분기를 하위 클래스(subclass)의 오버라이딩 메서드로 옮기고, 기존 상위 클래스의 메서드는 추상(abstract) 메서드로 변경한다 [1]. 이 기법을 통해 기존 코드를 수정하지 않고도 새로운 하위 클래스를 추가하여 아키텍처 변경을 관리하기 쉽게 만들 수 있다 [3].
|
||||
## 매 한 줄
|
||||
> **"매 type-discriminating switch/if-chain 을 매 polymorphic dispatch 로 교체"**. Fowler *Refactoring 2e* (2018) Ch.10. 매 type code 가 add 시마다 매 switch 들 모두 수정 필요한 shotgun surgery 의 표준 처방. 매 modern alternative — discriminated union + exhaustiveness, strategy map, pattern matching — 도 같은 본질을 공유한다.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
* **다형성 도입의 동기와 효과**
|
||||
* 타입 코드나 문자열에 기반해 동작을 결정하는 명시적 조건문의 작성을 피할 수 있다 [2].
|
||||
* 동일한 조건문 패턴이 프로그램의 여러 곳에 산재해 있을 때 가장 큰 이점을 제공한다 [2]. 새로운 타입을 추가하고자 할 때, 모든 조건문을 일일이 찾아 수정할 필요 없이 새로운 하위 클래스를 만들고 적절한 메서드만 제공하면 된다 [2, 4].
|
||||
* 각 조건 분기의 행동이 개별 클래스로 독립되어 구현되므로 코드를 테스트하기가 훨씬 쉬워지고, 클라이언트는 하위 클래스에 대해 알 필요가 없어 시스템의 의존성이 감소한다 [2-4].
|
||||
## 매 핵심
|
||||
|
||||
* **실행 절차 (Mechanics)**
|
||||
1. **상속 구조 생성:** 리팩토링을 시작하기 전, 다형성 동작을 수용할 적절한 상속 구조(Inheritance Structure)가 준비되어 있어야 한다 [5]. 기존 구조가 없다면 타입 코드를 하위 클래스로 바꾸거나(Replace Type Code with Subclasses) 상태/전략 패턴으로 바꾸는 기법(Replace Type Code with State/Strategy)을 사용하여 생성한다 [5, 6].
|
||||
2. **조건문 추출 및 이동:** 대상 조건문이 더 큰 메서드의 일부라면 먼저 `Extract Method`로 분리해 낸 후, 필요하다면 `Move Method`를 통해 상속 구조의 최상단으로 옮긴다 [7].
|
||||
3. **다형성 메서드 구현:** 각 하위 클래스 중 하나를 선택하여 조건문의 해당 분기 논리를 재정의(override) 메서드에 복사하고 알맞게 수정한다 [7].
|
||||
4. **조건 분기 제거 및 테스트:** 하위 클래스의 구현을 컴파일하고 독립적으로 테스트한 뒤, 원본 조건문에서 해당 분기를 제거한다 [3, 8].
|
||||
5. **추상화 완료:** 조건문의 모든 분기가 하위 클래스의 메서드로 전환될 때까지 동일한 과정을 반복한 후, 상위 클래스의 원본 메서드를 추상(abstract) 메서드로 선언한다 [8].
|
||||
### 매 trigger smell
|
||||
- 매 동일 `switch (kind)` 가 codebase 여러 곳에 반복.
|
||||
- 매 새 type 추가가 매 N 곳의 switch 수정 강제.
|
||||
- 매 default branch 가 silently incorrect.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
* **객체 수명 주기 내 클래스 변경 불가 문제:** 하위 클래스를 통해 다형성을 구현하는 방식을 선택할 때의 가장 큰 제약은 한 번 생성된 객체는 수명 주기 동안 자신의 클래스를 변경할 수 없다는 점이다 [9]. 만약 조건의 기준이 되는 속성(예: 영화의 분류 체계나 직원의 직급)이 런타임에 동적으로 변경되어야 한다면 단순한 하위 클래스 생성이 작동하지 않으므로, 다소 복잡하더라도 간접 참조를 포함하는 상태 패턴(State)이나 전략 패턴(Strategy)을 적용하여 다형성을 구성해야 한다 [9-11].
|
||||
* **과도한 추상화(Overkill)의 위험:** 단일 메서드에만 영향을 미치고 향후 조건의 종류가 변경될 가능성이 거의 없는 소수의 조건문이라면, 다형성을 도입하는 것은 오히려 불필요한 과잉 설계(overkill)가 될 수 있다 [12]. 이러한 경우에는 `Replace Parameter with Explicit Methods` 기법과 같은 다른 방식을 적용하는 것이 더 나은 선택일 수 있다 [12].
|
||||
* **선행 리팩토링 작업의 필수성:** 이 기법을 수행하기 위해서는 다형성을 처리할 상속 구조가 미리 준비되어야 하므로, 이를 위해 기존 코드의 타입 코드나 조건 변수를 객체화하는 선행 리팩토링 과정이 요구되어 초기 작업 비용이 발생한다 [5, 13].
|
||||
### 매 mechanics (Fowler)
|
||||
1. 매 self-encapsulating type 추출 (subclass 또는 strategy).
|
||||
2. 매 switch 한 case 를 method override 로 이동 (test 유지).
|
||||
3. 매 모든 case 이동 후 매 base method 를 abstract 화.
|
||||
4. 매 caller 에서 매 conditional 제거.
|
||||
|
||||
---
|
||||
*Last updated: 2026-05-03*
|
||||
### 매 응용
|
||||
1. Tax calculation: country-specific subclass.
|
||||
2. Bird movement: Penguin/Parrot/Owl `getSpeed()` override.
|
||||
3. Payment processor: Stripe/Toss/PayPal strategy.
|
||||
4. AST visitor: node type 별 dispatch.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
## 💻 패턴
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
### Before: type-code switch
|
||||
```typescript
|
||||
type Bird = {
|
||||
kind: 'penguin' | 'parrot' | 'owl';
|
||||
voltage?: number;
|
||||
isNailed?: boolean;
|
||||
numberOfCoconuts?: number;
|
||||
};
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
function plumage(bird: Bird): string {
|
||||
switch (bird.kind) {
|
||||
case 'penguin': return 'average';
|
||||
case 'parrot': return bird.isNailed ? 'tattered' : 'beautiful';
|
||||
case 'owl': return 'attentive';
|
||||
}
|
||||
}
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (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
|
||||
function airSpeed(bird: Bird): number {
|
||||
switch (bird.kind) {
|
||||
case 'penguin': return 50;
|
||||
case 'parrot': return 80 - 5 * (bird.voltage ?? 0);
|
||||
case 'owl': return 12 * (bird.numberOfCoconuts ?? 0);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### After: polymorphism (classes)
|
||||
```typescript
|
||||
abstract class Bird {
|
||||
abstract get plumage(): string;
|
||||
abstract get airSpeed(): number;
|
||||
}
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
class Penguin extends Bird {
|
||||
get plumage() { return 'average'; }
|
||||
get airSpeed() { return 50; }
|
||||
}
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
class Parrot extends Bird {
|
||||
constructor(private voltage = 0, private nailed = false) { super(); }
|
||||
get plumage() { return this.nailed ? 'tattered' : 'beautiful'; }
|
||||
get airSpeed() { return 80 - 5 * this.voltage; }
|
||||
}
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
class Owl extends Bird {
|
||||
constructor(private coconuts = 0) { super(); }
|
||||
get plumage() { return 'attentive'; }
|
||||
get airSpeed() { return 12 * this.coconuts; }
|
||||
}
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### Modern alternative: discriminated union + exhaustiveness
|
||||
```typescript
|
||||
type Bird =
|
||||
| { kind: 'penguin' }
|
||||
| { kind: 'parrot'; voltage: number; nailed: boolean }
|
||||
| { kind: 'owl'; coconuts: number };
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
function airSpeed(b: Bird): number {
|
||||
switch (b.kind) {
|
||||
case 'penguin': return 50;
|
||||
case 'parrot': return 80 - 5 * b.voltage;
|
||||
case 'owl': return 12 * b.coconuts;
|
||||
default: {
|
||||
const _exhaustive: never = b;
|
||||
return _exhaustive;
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Strategy map (data-driven dispatch)
|
||||
```typescript
|
||||
const speedStrategies = {
|
||||
penguin: () => 50,
|
||||
parrot: (b: { voltage: number }) => 80 - 5 * b.voltage,
|
||||
owl: (b: { coconuts: number }) => 12 * b.coconuts,
|
||||
} as const;
|
||||
|
||||
function airSpeed<K extends keyof typeof speedStrategies>(
|
||||
kind: K,
|
||||
data: Parameters<typeof speedStrategies[K]>[0],
|
||||
): number {
|
||||
return (speedStrategies[kind] as any)(data);
|
||||
}
|
||||
```
|
||||
|
||||
### Visitor (when ops > types)
|
||||
```typescript
|
||||
interface Visitor<R> {
|
||||
penguin(): R;
|
||||
parrot(b: { voltage: number; nailed: boolean }): R;
|
||||
owl(b: { coconuts: number }): R;
|
||||
}
|
||||
|
||||
class SpeedVisitor implements Visitor<number> {
|
||||
penguin() { return 50; }
|
||||
parrot(b: { voltage: number }) { return 80 - 5 * b.voltage; }
|
||||
owl(b: { coconuts: number }) { return 12 * b.coconuts; }
|
||||
}
|
||||
```
|
||||
|
||||
### Rust pattern matching (sister technique)
|
||||
```rust
|
||||
enum Bird {
|
||||
Penguin,
|
||||
Parrot { voltage: u32, nailed: bool },
|
||||
Owl { coconuts: u32 },
|
||||
}
|
||||
|
||||
impl Bird {
|
||||
fn air_speed(&self) -> u32 {
|
||||
match self {
|
||||
Bird::Penguin => 50,
|
||||
Bird::Parrot { voltage, .. } => 80 - 5 * voltage,
|
||||
Bird::Owl { coconuts } => 12 * coconuts,
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| OOP language, type 자주 add | Subclass polymorphism |
|
||||
| FP/TS, op 자주 add | Discriminated union + match (expression problem) |
|
||||
| 매 dispatch table 단순 | Strategy map (object literal) |
|
||||
| Op 많고 type 안정적 | Visitor |
|
||||
| Type 많고 op 안정적 | Sum type + match |
|
||||
| 매 single-use switch | 매 그대로 두기 — refactor cost > benefit |
|
||||
|
||||
**기본값**: TS — discriminated union + exhaustive switch. OOP-heavy domain — subclass.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Refactoring_Best_Practices]] · [[Polymorphism]]
|
||||
- 변형: [[Strategy Pattern]] · [[State Pattern]] · [[Visitor Pattern]]
|
||||
- 응용: [[Discriminated Union]] · [[Pattern Matching]] · [[Open-Closed Principle]]
|
||||
- Adjacent: [[Replace Type Code with Subclasses]] · [[Expression Problem]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 codebase 에 매 동일 switch 가 3+ 곳, 매 새 type 추가가 자주, 매 OCP 위반 가시.
|
||||
**언제 X**: 매 switch 1 곳, 매 type 안정적, 매 small dispatch — over-engineering.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Inheritance for everything**: 매 deep hierarchy — composition + interface 권장.
|
||||
- **Polymorphism without exhaustiveness**: 매 default branch 가 silent bug 숨김.
|
||||
- **Anemic subclass**: 매 method 1개 차이 — strategy 가 더 적합.
|
||||
- **Refactor without tests**: 매 behavior preservation 의 보증 없음.
|
||||
- **`instanceof` chain**: 매 polymorphism 의 antithesis — 매 새 switch 의 변종.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified: Fowler *Refactoring 2e* (2018) Ch.10 "Replace Conditional with Polymorphism"; refactoring.com.
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — Fowler mechanics + modern union/strategy/visitor variants |
|
||||
|
||||
Reference in New Issue
Block a user