리팩터링(Refactoring)은 외부 동작은 유지하면서 내부 코드 구조를 개선하는 작업이다. 새 기능 추가 없이 가독성, 유지보수성, 성능을 향상시킨다. Martin Fowler가 체계화했으며 테스트 커버리지가 안전망 역할을 한다.
핵심 원칙
리팩터링은 기능 변경과 구분된 별도의 작업이다.
- •리팩터링 중에는 새 기능을 추가하지 않는다
- •각 단계 후 테스트를 실행해 동작이 유지됨을 확인한다
- •작은 단계로 나누어 안전하게 진행한다
주요 리팩터링 기법
python
# Before: 너무 긴 함수
def process_order(order):
# 금액 계산
subtotal = sum(item.price * item.qty for item in order.items)
tax = subtotal * 0.1
total = subtotal + tax
# 배송비 계산
if order.weight > 5:
shipping = 5000
else:
shipping = 2500
return total + shipping
# After: 책임 분리
def calculate_total(items):
subtotal = sum(item.price * item.qty for item in items)
return subtotal * 1.1
def calculate_shipping(weight):
return 5000 if weight > 5 else 2500
def process_order(order):
return calculate_total(order.items) + calculate_shipping(order.weight)
매직 넘버 제거
python
# Before
if status == 2:
send_email()
# After
APPROVED = 2
if status == APPROVED:
send_email()
조건문 단순화
python
# Before (부정 조건)
if not (age < 18 or not has_license):
allow_driving()
# After (의도 명확)
def can_drive(age, has_license):
return age >= 18 and has_license
if can_drive(age, has_license):
allow_driving()
코드 스멜 (Code Smell)
리팩터링이 필요한 신호:
- •중복 코드 (DRY 위반)
- •긴 메서드 (20줄 이상)
- •긴 파라미터 목록 (4개 이상)
- •산탄총 수술 (하나의 변경이 여러 클래스를 수정)
- •주석으로 설명해야 하는 코드
관련 개념
참고문헌
- •Fowler, M. (2018). Refactoring: Improving the Design of Existing Code, 2nd Ed.