IT책, 강의/리팩터링
10 - 조건부 로직 간소화 - 제어 플래그를 탈출문으로 바꾸기
제로칼로리
2023. 9. 11. 17:52
개요
제어 플래그란 코드 동작을 변경하는 데 사용되는 변수
어딘가에서 값을 계산해 다른 어딘가 조건문에 쓰인다.
즉, 계산과 평가가 한 곳에서 이루어 지지지 않는다.
제어 플래그는 반목문(혹은 재귀)에 주로 존재한다.
예시
function eaxmple(){ let found = false; for(const p of people){ if( ! found){ if(p === "조커"){ sendAlert(); found = true; } if(p === "사루만"){ sendAlert(); found = true; } } } } |
function eaxmple(){ checkForMiscreants(people); } //함수로 추출 function checkForMiscreants(people) { let found = false; for (const p of people) { if (!found) { if (p === "조커") { sendAlert(); found = true; } if (p === "사루만") { sendAlert(); found = true; } } } } |
function eaxmple(){ checkForMiscreants(people); } //함수로 추출 function checkForMiscreants(people) { let found = false; for (const p of people) { if (!found) { if (p === "조커") { sendAlert(); found = true; } if (p === "사루만") { sendAlert(); found = true; } } } } |
function checkForMiscreants(people) { let found = false; for (const p of people) { if (!found) { if (p === "조커") { sendAlert(); // found = true; return; } if (p === "사루만") { sendAlert(); // found = true; return; } } } } |
function checkForMiscreants(people) { for (const p of people) { if (p === "조커") { sendAlert(); return; } if (p === "사루만") { sendAlert(); return; } } } |
//더 가다듬기 function checkForMiscreants(people) { if(people.some(p=>["조커","사루만"].includes(p))) sendAlert(); } |