Files
2nd/10_Wiki/Topics/Architecture/리팩토링 원칙.md
T
Antigravity Agent f8b21af4be Wiki cleanup: error-doc removal, dedup merge, link normalization
10_Wiki/Topics 대규모 정리:
- 오류 캡처/미완성 stub 문서 227개 제거
- 교차폴더 중복 43클러스터 병합 (63파일 → redirect)
- 링크명 정규화: 깨진 링크 수정·redirect 직결·개념 매핑 ~2,400건
- 카테고리 MOC 6개 신규 생성
- Graph 섹션 미해결 related-keyword 링크 10,058건 제거

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 23:52:15 +09:00

4.6 KiB

id, title, category, status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, verification_status, tags, raw_sources, last_reinforced, github_commit, tech_stack
id title category status canonical_id aliases duplicate_of source_trust_level confidence_score verification_status tags raw_sources last_reinforced github_commit tech_stack
wiki-2026-0508-리팩토링-원칙 리팩토링 원칙 10_Wiki/Topics verified self
Refactoring Principles
리팩토링 가이드라인
none A 0.9 applied
refactoring
code-quality
principles
2026-05-10 pending
language framework
polyglot ide-tooling

리팩토링 원칙

매 한 줄

"매 small step, green test, no behavior change". Fowler 의 1999 정의 그대로 — 매 외부 동작 보존, 내부 구조 개선. 2026 에 LLM-assisted refactor 가 boilerplate-level change 를 자동화하지만, 매 design intent 의 보존은 여전히 사람의 책임.

매 핵심

매 3대 원칙

  • Behavior preservation: 매 test suite green 유지. Red 면 commit X.
  • Small steps: 매 1 commit = 1 transformation. revert 가능해야.
  • Refactor ≠ Rewrite: 매 새 feature 추가 X. 매 bug fix X. 매 oranges-to-oranges.

매 Two Hats (Kent Beck)

  • "Adding feature" hat 또는 "Refactoring" hat — 매 동시 X.
  • Hat 전환 시 commit boundary.

매 응용

  1. Pre-feature refactor: 매 새 기능 추가 전에 매 ground 정리.
  2. Code smell 감지 시 즉시 처리 (Boy Scout Rule).
  3. PR review 에서 매 reviewer-suggested refactor 는 별도 PR.

💻 패턴

Extract Function

# Before
def process_order(order):
    if order.total > 100 and order.customer.tier == "gold":
        order.discount = order.total * 0.1
    # ... more logic

# After
def process_order(order):
    if _is_eligible_for_gold_discount(order):
        order.discount = order.total * 0.1

def _is_eligible_for_gold_discount(order):
    return order.total > 100 and order.customer.tier == "gold"

Replace Magic Number

// Before
if (user.age >= 18) { ... }

// After
const LEGAL_ADULT_AGE = 18;
if (user.age >= LEGAL_ADULT_AGE) { ... }

Replace Conditional with Polymorphism

# Before
def calculate_pay(employee):
    if employee.type == "salaried":
        return employee.monthly_salary
    elif employee.type == "hourly":
        return employee.hours * employee.rate

# After
class SalariedEmployee:
    def pay(self): return self.monthly_salary

class HourlyEmployee:
    def pay(self): return self.hours * self.rate

Introduce Parameter Object

// Before
function createUser(name, email, phone, address, city, country) { ... }

// After
interface UserProfile {
  name: string; email: string; phone: string;
  address: string; city: string; country: string;
}
function createUser(profile: UserProfile) { ... }

Inline Variable

# Before
price_basis = order.quantity * order.item_price
return price_basis > 1000

# After
return order.quantity * order.item_price > 1000

LLM-Assisted Rename (Claude Opus 4.7)

# claude code refactor --rename "calc" --to "calculateTotal" \
#   --scope src/ --dry-run
# Reviews semantic usages, not just textual replace.

매 결정 기준

상황 Approach
Test 없음 매 먼저 characterization test 작성
Behavior change 필요 매 refactor 아님 — feature work 으로 분리
Large class (1000+ lines) Extract Class 점진적 적용
Duplicated code (3+ sites) Rule of Three — extract
Legacy code, no tests Sprout Method / Sprout Class (Feathers)

기본값: small commit + green test + IDE refactoring tool 사용.

🔗 Graph

🤖 LLM 활용

언제: 매 boilerplate transformation (rename, extract, format), 매 unfamiliar legacy code 의 의도 파악, 매 test scaffolding 자동 생성. 언제 X: 매 design decision 이 필요한 architectural refactor — 매 LLM 은 local view 만 봄.

안티패턴

  • Refactoring + Feature mix: 매 PR 비대 + review 불가능.
  • Big bang refactor: 매 2주 stop-the-world refactor — merge conflict 폭탄.
  • Test-less refactor: 매 behavior preservation 증명 불가.
  • Cosmetic-only: 매 readability 개선 없는 style change 만 — review 시간 낭비.

🧪 검증 / 중복

  • Verified (Fowler, Refactoring 2nd ed., 2018; Beck, Tidy First? 2024).
  • 신뢰도 A.

🕓 Changelog

날짜 변경
2026-05-08 Phase 1
2026-05-10 Manual cleanup — Fowler/Beck 원칙 + 6 patterns + LLM-assisted refactor 추가