[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,95 +2,204 @@
|
||||
id: wiki-2026-0508-code-refactoring
|
||||
title: Code Refactoring
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-REINFORCE-AUTO-WIKI-DEV-002]
|
||||
aliases: [Refactoring, Code Improvement, Fowler Refactoring]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.95
|
||||
tags: [development, refactoring, code-quality, maintainability, technical-debt, p-reinforce]
|
||||
verification_status: applied
|
||||
tags: [refactoring, code-quality, fowler, ide, llm-refactor]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-01
|
||||
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: Polyglot
|
||||
framework: IDE/AST-based-tools
|
||||
---
|
||||
|
||||
# [[Code Refactoring]]
|
||||
# Code Refactoring
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "시스템의 겉보기 동작(Behavior)은 유지한 채 내부 구조를 개선하여, 인간에게는 더 읽기 쉽고 시스템에게는 더 변화에 유연하게 만드는 지속적인 코드 정제 작업."
|
||||
## 매 한 줄
|
||||
> **"매 refactoring = 매 외부 동작은 그대로 두고 internal 구조만 개선하는 disciplined transformation."**. 매 Martin Fowler 1999 "Refactoring" 이 catalog 화한 70+ named transformation 이 backbone, 매 2026 현재 IDE automated refactor + LLM-assisted refactor (Claude Opus 4.7, Cursor) 가 manual rewrite 대체. 매 핵심 disciplines = small steps + green tests + commit per refactor.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
리팩토링은 기술 부채를 관리하고 소프트웨어의 생명력을 유지하는 핵심 활동입니다.
|
||||
## 매 핵심
|
||||
|
||||
1. **목적의 분리 (Separation of Concerns)**:
|
||||
* **기능 추가와 리팩토링의 분리**: 새로운 기능 구현과 코드 구조 개선은 반드시 별도의 풀 리퀘스트(PR)로 진행해야 합니다. 섞일 경우 리뷰어의 인지 부하가 급증하고 검증의 정확도가 떨어집니다.
|
||||
* **스타일 수정의 독립성**: 포맷팅이나 명칭 변경과 같은 리팩토링도 기능 변경과 섞지 않는 것이 원칙입니다.
|
||||
2. **안전망 확보**:
|
||||
* 리팩토링의 전제 조건은 견고한 **자동화 테스트**입니다. 로직 개선 후에도 기존 기능이 완벽히 작동함을 증명할 수 있어야 합니다.
|
||||
3. **효율적 전략**:
|
||||
* 대규모 리팩토링은 한 번에 처리하기보다 200~400줄 단위로 잘게 쪼개어(Decomposition) 단계적으로 진행하는 것이 리뷰 품질과 속도 면에서 유리합니다.
|
||||
### 매 catalog (대표)
|
||||
- **Extract Function / Method**: 매 코드 블록 → 새 function.
|
||||
- **Inline Function**: 매 trivial wrapper 제거.
|
||||
- **Rename**: 매 의미 명확한 이름.
|
||||
- **Extract Variable / Inline Variable**.
|
||||
- **Move Function / Field**: 매 right class/module 로.
|
||||
- **Replace Conditional with Polymorphism**.
|
||||
- **Replace Magic Number with Constant**.
|
||||
- **Introduce Parameter Object**.
|
||||
- **Decompose Conditional**.
|
||||
- **Extract Class / Inline Class**.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **리뷰 지연의 부작용**: 코드 리뷰 프로세스가 너무 느리면 개발자들은 리팩토링이나 코드 정리를 기피하게 되어 장기적으로 기술 부채가 누적됩니다. 빠른 리뷰 피드백 루프가 건강한 리팩토링 문화를 만듭니다.
|
||||
- **사후 비용 vs 사전 설계**: 개발 완료 후의 리팩토링은 비용이 많이 듭니다. 아키텍처 리뷰를 통한 사전 설계 검토(Shift-Left)가 대규모 리팩토링을 예방하는 가장 효율적인 정책입니다.
|
||||
### 매 disciplines
|
||||
- **Tests first**: 매 refactor 전 green test suite.
|
||||
- **Small steps**: 매 single refactor → run tests → commit.
|
||||
- **No mixing**: 매 behavior change 와 refactor 동시 X.
|
||||
- **Reversibility**: 매 step 별 git revert 가능.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Technical Debt]]: 리팩토링이 상환하고자 하는 비용.
|
||||
- [[Automated Testing]]: 리팩토링을 가능하게 하는 안전망.
|
||||
- [[Code Health]]: 리팩토링의 궁극적인 지향점.
|
||||
- [[Single-purpose PR]]: 리팩토링 시 준수해야 할 PR 정책.
|
||||
- [[Architecture Review]]: 대규모 리팩토링을 예방하는 선제적 대응.
|
||||
---
|
||||
### 매 응용
|
||||
1. **Legacy modernization**: 매 strangler fig + extract.
|
||||
2. **Performance**: 매 inline hot function, extract slow path.
|
||||
3. **Test enabling**: 매 dependency 분리.
|
||||
4. **Onboarding**: 매 confusing code rename + decompose.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
## 💻 패턴
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
### Extract Function
|
||||
```python
|
||||
# BEFORE
|
||||
def print_owing(invoice):
|
||||
print_banner()
|
||||
outstanding = sum(o.amount for o in invoice.orders)
|
||||
print(f"name: {invoice.customer}")
|
||||
print(f"amount: {outstanding}")
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
# AFTER
|
||||
def print_owing(invoice):
|
||||
print_banner()
|
||||
outstanding = calculate_outstanding(invoice)
|
||||
print_details(invoice, outstanding)
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
def calculate_outstanding(invoice):
|
||||
return sum(o.amount for o in invoice.orders)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
def print_details(invoice, outstanding):
|
||||
print(f"name: {invoice.customer}")
|
||||
print(f"amount: {outstanding}")
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Replace Conditional with Polymorphism
|
||||
```typescript
|
||||
// BEFORE
|
||||
function pay(employee: Employee) {
|
||||
switch (employee.type) {
|
||||
case 'engineer': return baseSalary(employee);
|
||||
case 'salesman': return baseSalary(employee) + commission(employee);
|
||||
case 'manager': return baseSalary(employee) + bonus(employee);
|
||||
}
|
||||
}
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
// AFTER
|
||||
abstract class EmployeeType {
|
||||
abstract pay(e: Employee): number;
|
||||
}
|
||||
class Engineer extends EmployeeType { pay(e) { return baseSalary(e); } }
|
||||
class Salesman extends EmployeeType { pay(e) { return baseSalary(e) + commission(e); } }
|
||||
class Manager extends EmployeeType { pay(e) { return baseSalary(e) + bonus(e); } }
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Introduce Parameter Object
|
||||
```python
|
||||
# BEFORE
|
||||
def amount_invoiced(start_date, end_date, customer_id, currency, ...): ...
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
# AFTER
|
||||
@dataclass
|
||||
class InvoiceQuery:
|
||||
range: DateRange
|
||||
customer_id: str
|
||||
currency: str
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
def amount_invoiced(q: InvoiceQuery): ...
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### Decompose Conditional
|
||||
```javascript
|
||||
// BEFORE
|
||||
if (date.before(SUMMER_START) || date.after(SUMMER_END)) {
|
||||
charge = quantity * winterRate + winterServiceCharge;
|
||||
} else {
|
||||
charge = quantity * summerRate;
|
||||
}
|
||||
|
||||
// AFTER
|
||||
charge = isSummer(date) ? summerCharge(quantity) : winterCharge(quantity);
|
||||
function isSummer(d) { return !d.before(SUMMER_START) && !d.after(SUMMER_END); }
|
||||
function summerCharge(q) { return q * summerRate; }
|
||||
function winterCharge(q) { return q * winterRate + winterServiceCharge; }
|
||||
```
|
||||
|
||||
### Strangler Fig (legacy migration)
|
||||
```typescript
|
||||
// route table — gradually shift endpoints to new service
|
||||
const routes = {
|
||||
'/users': process.env.NEW_USERS === 'on' ? newUsers : legacyUsers,
|
||||
'/orders': process.env.NEW_ORDERS === 'on' ? newOrders : legacyOrders,
|
||||
'/billing': legacyBilling, // not migrated yet
|
||||
};
|
||||
// flip flags one at a time, rollback by env var
|
||||
```
|
||||
|
||||
### IDE-driven (IntelliJ / Roslyn)
|
||||
```bash
|
||||
# JetBrains command-line refactor (CI batch)
|
||||
idea.sh inspect $PROJECT inspectionProfile.xml output/ \
|
||||
-d $MODULE -v2
|
||||
|
||||
# C# Roslyn analyzer + code fix runs in `dotnet format analyzers --verify-no-changes`
|
||||
```
|
||||
|
||||
### LLM-assisted refactor (Claude Opus 4.7)
|
||||
```bash
|
||||
# 1. select scope, 2. generate diff, 3. tests must stay green
|
||||
claude refactor \
|
||||
--scope src/billing/ \
|
||||
--instruction "Extract OrderTotalCalculator class; preserve all behavior" \
|
||||
--validate "pytest tests/billing/"
|
||||
# Claude proposes diff → run tests → commit if green
|
||||
```
|
||||
|
||||
### Test characterization (legacy without tests)
|
||||
```python
|
||||
# Before refactor of untested code: write golden tests first
|
||||
def test_legacy_charge_2025_invoice():
|
||||
inv = load_fixture('2025_invoice.json')
|
||||
expected = legacy.calc(inv) # capture current behavior
|
||||
assert refactored.calc(inv) == expected # equality, not "correctness"
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Refactor |
|
||||
|---|---|
|
||||
| Long function (> 30 lines) | Extract Function |
|
||||
| Same param list 5+ places | Introduce Parameter Object |
|
||||
| `switch (type)` repeated | Replace Conditional with Polymorphism |
|
||||
| Confusing name | Rename |
|
||||
| Class doing 2 things | Extract Class |
|
||||
| Legacy without tests | Characterization tests first |
|
||||
| Mass code movement | LLM batch + test-gate |
|
||||
|
||||
**기본값**: small step + commit per refactor + tests green; LLM 으로 mass rename / extract 가속.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Software_Engineering]] · [[Code_Quality]]
|
||||
- 변형: [[Strangler_Fig]] · [[Mikado_Method]]
|
||||
- 응용: [[Legacy_Modernization]] · [[Test_Driven_Development]]
|
||||
- Adjacent: [[Martin_Fowler]] · [[Clean_Code]] · [[Design_Patterns]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: bulk rename, extract function, polymorphism conversion, parameter object 도입.
|
||||
**언제 X**: subtle concurrency / lock-free invariants — 매 manual review 필수.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Refactor + feature in same commit**: 매 review/revert 불가능.
|
||||
- **Refactor without tests**: 매 silent behavior change.
|
||||
- **Big-bang rewrite**: 매 6개월 후 production 되돌리기 불가능.
|
||||
- **Premature abstraction**: 매 1번 쓰인 패턴 인터페이스화 — YAGNI.
|
||||
- **Trust-LLM-and-skip-tests**: 매 LLM hallucinated edge case 통과시킴.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Fowler "Refactoring" 2nd ed 2018, "Working Effectively with Legacy Code" Feathers 2004).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — Fowler catalog, disciplines, IDE/LLM-assisted patterns |
|
||||
|
||||
Reference in New Issue
Block a user