티스토리 뷰




//03. 중첩 조건문(if) 개선하기

// 중첩된 if문
if (color) {
  if (color === 'black') {
    printBlackBackground();
  } else if (color === 'red') {
    printRedBackground();
  } else if (color === 'blue') {
    printBlueBackground();
  } else if (color === 'green') {
    printGreenBackground();
  } else {
    printYellowBackground();
  }
}

// swith 문 사용 개선 #1
// 추천하지 않는다. 디버깅 어렵다 ( https://toddmotto.com/deprecating-the-switch-statement-for-object-literals/ ) 이유안내
switch(color) {
  case 'black':
    printBlackBackground();
    break;
  case 'red':
    printRedBackground();
    break;
  case 'blue':
    printBlueBackground();
    break;
  case 'green':
    printGreenBackground();
    break;
  default:
    printYellowBackground();
}

// 만약 몇몇 조건이 추가되면 어떻게 할 것인가 ? 불 필요하게 switch 문에 조건을 달 필요가 있을까?
switch(true) {
  case (typeof color === 'string' && color === 'black'):
    printBlackBackground();
    break;
  case (typeof color === 'string' && color === 'red'):
    printRedBackground();
    break;
  case (typeof color === 'string' && color === 'blue'):
    printBlueBackground();
    break;
  case (typeof color === 'string' && color === 'green'):
    printGreenBackground();
    break;
  case (typeof color === 'string' && color === 'yellow'):
    printYellowBackground();
    break;
}


// swicth 문과 조건문의 피하고 object 사용하여 처리하는 방법이 실력있게 처리한 방법이라 할수 있겟당.
var colorObj = {
  'black': printBlackBackground,
  'red': printRedBackground,
  'blue': printBlueBackground,
  'green': printGreenBackground,
  'yellow': printYellowBackground
};

if (color && colorObj.hasOwnProperty(color)) {
  colorObj[color]();
}
// ( 더 자세히 설명한 내용 ) http://www.nicoespeon.com/en/2015/01/oop-revisited-switch-in-js/

댓글
D-DAY
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함