Replace Nested Conditional With Guard Clauses, ์ค์ฒฉ ์กฐ๊ฑด๋ฌธ์ ๋ณดํธ ๊ตฌ๋ฌธ์ผ๋ก ๋ฐ๊พธ๊ธฐ๋ฅผ ์์๋ณด์.
์์ฝ
์ฝ๋
function getPayAmount() {
let result;
if (isDead) result = deadAmount();
else {
if (isSeparated) result = separatedAmount();
else {
if (isRetired) result = retiredAmount();
else result = normalPayAmount();
}
}
return result;
}
function getPayAmount() {
if (isDead) return deadAmount();
if (isSeparated) return separatedAmount();
if (isRetired) return retiredAmount();
return normalPayAmount();
}
๋ฐฐ๊ฒฝ
- ์กฐ๊ฑด๋ฌธ์ด ์ฌ์ฉ๋๋ ๊ฒฝ์ฐ๋ ๋๊ฐ์ง๋ค.
- ์ฐธ์ด๊ฑฐ๋ ๊ฑฐ์ง์ธ ๊ฒฝ์ฐ ๋ชจ๋๊ฐ ์ ์๋์์ผ๋ก ์ด์ด์ ธ์ผ ํ๋ ๊ฒฝ์ฐ
- ์ฐธ์ธ ๊ฒฝ์ฐ๋ง ์๋ฏธ๊ฐ ์๊ณ , ๊ทธ๋ ์ง ์์ ๊ฒฝ์ฐ ์์ธ ์ฒ๋ฆฌ๋ฅผ ํด์ผ ํ๋ ๊ฒฝ์ฐ
- ์ ๋๊ฐ์ง ๊ฒฝ์ฐ๋ ์๋ํ๋ ๋ฐ๊ฐ ๋ค๋ฅด๋, ์ด ์๋๊ฐ ํํ๋ก ๋๋ฌ๋๋ ๊ฒ์ด ์ณ๋ค.
swift
์์๋guard
๊ตฌ๋ฌธ์ ์ฌ์ฉํ๋ค.
์ ์ฐจ
- ๊ต์ฒดํด์ผ ํ ์กฐ๊ฑด ์ค ๊ฐ์ฅ ๋ฐ๊นฅ ๊ฒ์ ์ ํํ์ฌ ๋ณดํธ ๊ตฌ๋ฌธ์ผ๋ก ๋ฐ๊พผ๋ค.
- ํ ์คํธํ๋ค.
- 1~2๋ฅผ ํ์ํ ๋งํผ ๋ฐ๋ณตํ๋ค.
- ๋ชจ๋ ๋ณดํธ ๊ตฌ๋ฌธ์ด ๊ฐ์ ๊ฒฐ๊ณผ๋ฅผ ๋ฐํํ๋ค๋ฉด, ์กฐ๊ฑด๋ฌธ์ ํตํฉํ๋ค.
์์
function payAmount(employee) {
let result;
if (employee.isSeparated) result = {amount: 0, reasonCode: "SEP"};
else {
if (employee.isRetired) result = {amount: 0, reasonCode: "RET"};
else {
// ๊ธ์ฌ ๊ณ์ฐ ๋ก์ง
lorem.ipsum(dolor.sitAmet);
consectetur(adipiscing).elit();
sed.do.eiusmod = tempor.incididunt.ut(labore) && dolore(magna.aliqua);
ut.enim.ad(minim.veniam);
result = someFinalComputation();
}
}
return result;
}
- ๋๋์ฒด ๋ญํ๋์ง ํ์ฐํ ๋๋ฌ๋์ง ์๋๋ค.
- ์ด ์ด์ ๋ ์ค์ฒฉ๋ ์กฐ๊ฑด๋ค์ด ์๊ธฐ ๋๋ฌธ์ด๋ค.
- ์ ๋ณด๋ฉด, ๋ชจ๋ ์กฐ๊ฑด์ด ๊ฑฐ์ง์ธ ์ํฉ์ ๊ณ์ฐ์ ํ๊ณ ์๋ ๊ฒ์ ์ ์ ์๋ค.
function payAmount(employee) {
let result;
if (employee.isSeparated) return {amount: 0, reasonCode: "SEP"};
if (employee.isRetired) {
result = {amount: 0, reasonCode: "RET"};
}
else {
// ๊ธ์ฌ ๊ณ์ฐ ๋ก์ง
lorem.ipsum(dolor.sitAmet);
consectetur(adipiscing).elit();
sed.do.eiusmod = tempor.incididunt.ut(labore) && dolore(magna.aliqua);
ut.enim.ad(minim.veniam);
result = someFinalComputation();
}
return result;
}
- ์ผ๋จ ๊ฐ์ฅ ์ฒ์์ ๋ง๋๋ ์กฐ๊ฑด์ ๋ํด
result
์ ๋ด์ง ์๊ณreturn
์์ผฐ๋ค. - ์ด๋ฐ์์ผ๋ก ๋ง๋๋ ์กฐ๊ฑด๋ค์ ๋ํด early return์ ์ํค๋ฉด, ์ฝ๋๊ฐ ๋ณด๋ค ๋ช ํํด์ง๋ค.
function payAmount(employee) {
if (employee.isSeparated) return {amount: 0, reasonCode: "SEP"};
if (employee.isRetired) return {amount: 0, reasonCode: "RET"};
// ๊ธ์ฌ ๊ณ์ฐ ๋ก์ง
lorem.ipsum(dolor.sitAmet);
consectetur(adipiscing).elit();
sed.do.eiusmod = tempor.incididunt.ut(labore) && dolore(magna.aliqua);
ut.enim.ad(minim.veniam);
return someFinalComputation();
}