Refactoring (리펙토링)
[Refactoring] 9-1. 조건부 로직 최소화 (조건문 분해하기)
jake-kim
2023. 5. 27. 01:19
조건문 분해하기
- 조건문에서 중요한 것
- 조건문에서 무슨 일이 일어나는지 이야기해주지만 '왜'가 들어나는 코드가 필요
- 조건문들을 함수로 만들어서 조건의 의도가 분명하게 들어나도록 수정이 필요
// '어떻게'만 나타난 조건문 - 조건문이 길어지게되면, 조거문 안에 블록문에서 일어나는 이유를 파악하기가 힘듦
if 20 < jake.age && jake.plan.summerStart < jake.plan.reservationDate {
charge = basePrice * 2
} else {
charge = basePrice
}
// '왜'의 의미가 있는 있는 조건문 - 조건문을 추상화하여, 조건문 안에 charge = basePrice * 2의 이유를 파악하기 쉬움
if adult() && summer() {
charge = basePrice * 2
} else {
charge = basePrice
}

- 조건문을 하나하나 파악하고 나서야 드디어 이 조건문들이 무엇을 말하는지 알게 되는 경우가 있는데, 이때도 이 조건문들을 하나의 함수로 빼내면 의도가 명확하게 들어날 수 있음
let isUserLoggedIn = true
let hasSubscription = false
let isAdmin = false
let isTrialPeriodExpired = true
if isUserLoggedIn {
if hasSubscription {
if isAdmin {
print("관리자로 로그인되었습니다.")
} else {
if isTrialPeriodExpired {
print("로그인되었습니다. 구독이 만료되었습니다.")
} else {
print("로그인되었습니다. 구독이 활성화되었습니다.")
}
}
} else {
print("로그인되었습니다. 구독을 시작해주세요.")
}
} else {
print("로그인이 필요합니다.")
}
- 리펙토링 - 하나의 함수로 빼내어 복잡한 분기문들의 의도를 명확히 할 수 있음
func checkSubscribing(isUserLoggedIn: Bool, hasSubscription: Bool, isAdmin: Bool, isTrialPeriodExpired: Bool) {
if isUserLoggedIn {
if hasSubscription {
if isAdmin {
print("관리자로 로그인되었습니다.")
} else {
if isTrialPeriodExpired {
print("로그인되었습니다. 구독이 만료되었습니다.")
} else {
print("로그인되었습니다. 구독이 활성화되었습니다.")
}
}
} else {
print("로그인되었습니다. 구독을 시작해주세요.")
}
} else {
print("로그인이 필요합니다.")
}
}
checkSubscribing(isUserLoggedIn: true, hasSubscription: true, isAdmin: false, isTrialPeriodExpired: true)
* 전체 코드: https://github.com/JK0369/ExRefactoring9_1
* 참고
- Refactoring (Martin Flowler)