---
id: wiki-2026-0508-code-refactoring
title: Code Refactoring
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [Refactoring, Code Improvement, Fowler Refactoring]
duplicate_of: none
source_trust_level: A
confidence_score: 0.95
verification_status: applied
tags: [refactoring, code-quality, fowler, ide, llm-refactor]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
  language: Polyglot
  framework: IDE/AST-based-tools
---

# Code Refactoring

## 매 한 줄
> **"매 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.

## 매 핵심

### 매 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**.

### 매 disciplines
- **Tests first**: 매 refactor 전 green test suite.
- **Small steps**: 매 single refactor → run tests → commit.
- **No mixing**: 매 behavior change 와 refactor 동시 X.
- **Reversibility**: 매 step 별 git revert 가능.

### 매 응용
1. **Legacy modernization**: 매 strangler fig + extract.
2. **Performance**: 매 inline hot function, extract slow path.
3. **Test enabling**: 매 dependency 분리.
4. **Onboarding**: 매 confusing code rename + decompose.

## 💻 패턴

### 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}")

# AFTER
def print_owing(invoice):
    print_banner()
    outstanding = calculate_outstanding(invoice)
    print_details(invoice, outstanding)

def calculate_outstanding(invoice):
    return sum(o.amount for o in invoice.orders)

def print_details(invoice, outstanding):
    print(f"name: {invoice.customer}")
    print(f"amount: {outstanding}")
```

### 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);
  }
}

// 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); } }
```

### Introduce Parameter Object
```python
# BEFORE
def amount_invoiced(start_date, end_date, customer_id, currency, ...): ...

# AFTER
@dataclass
class InvoiceQuery:
    range: DateRange
    customer_id: str
    currency: str

def amount_invoiced(q: InvoiceQuery): ...
```

### 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
- 부모: [[Code_Quality]]
- 변형: [[Strangler_Fig]]
- 응용: [[Legacy_Modernization]] · [[Test-Driven Development]]
- Adjacent: [[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 |
