(번역)🧐 If-else,switch를 쓰지말고 Object Literals를 써라

chloe·2021년 11월 8일
7

Javascript

목록 보기
13/13
post-thumbnail

If-else 나 Switch를 쓰지말고 Object Literals를 사용하라.

자바스크립트에서 복잡한 조건문을 쓰는 것은, 항상 지저분한 코드를 작성할 가능성이 있다.
다수의 조건문의 경우,Object literal이 코드를 구조화하는 가장 읽기 좋은 방법이라고 생각한다.

예시를 보면, 운율이 있는 슬랭 구문과 그 의미를 리턴하는 함수가 있다고 가정하자.
If/else문을 사용해서 봐보자.

function getTranslation(rhyme) {
  if (rhyme.toLowerCase() === "apples and pears") {
    return "Stairs";
  } else if (rhyme.toLowerCase() === "hampstead heath") {
    return "Teeth";
  } else if (rhyme.toLowerCase() === "loaf of bread") {
    return "Head";
  } else if (rhyme.toLowerCase() === "pork pies") {
    return "Lies";
  } else if (rhyme.toLowerCase() === "whistle and flute") {
    return "Suit";
  }
  return "Rhyme not found";
}

흠.. 좋지 않다.가독성이 좋지 않을 뿐만 아니라,매 조건문마다 toLowerCase()를 반복하기 떄문이다.
우리는 switch문을 사용하거나 함수 시작시 변수에 lowercased rhyme을 할당하여 반복을 피할 수 있다.
switch문을 사용한 예시를 봐보자.

function getTranslation(rhyme) {
  switch (rhyme.toLowerCase()) {
    case "apples and pears":
      return "Stairs";
    case "hampstead heath":
      return "Teeth";
    case "loaf of bread":
      return "Head";
    case "pork pies":
      return "Lies";
    case "whistle and flute":
      return "Suit";
    default:
      return "Rhyme not found";
  }
}

toLowerCase()를 한번만 호출했지만, 여전히 가독성은 그리 좋지 않다.
그리고 Switch문은 오류가 발생하기 쉽다. 이런 경우, 값만 리턴하는 것이다.
그러나, 기능이 더 복잡해지만 break문을 놓치기 쉽고 버그를 마주하기 쉬워진다.

Object Literals를 대안으로 사용해보자

function getTranslationMap(rhyme) {
  const rhymes = {
    "apples and pears": "Stairs",
    "hampstead heath": "Teeth",
    "loaf of bread": "Head",
    "pork pies": "Lies",
    "whistle and flute": "Suit",
  };
  return rhymes[rhyme.toLowerCase()] ?? "Rhyme not found";
}

key는 조건이고 value는 응답인 Object가 있다. 그런 다음 square bracket[]을 사용해
전달한 rhyme에서 객체의 정확한 value값을 선택하여 사용할 수 있다.

마지막 줄의 ?? "Rhyme not found"는 default값으로 할당하기 위해 null 병합 연산자를 사용한 것이다. 이 부분의 뜻은 만약 rhymes[rhyme.toLowerCase()]가 null이거나 undefined인 경우( 그러나 false, 0은 아님), default string인 "Rhyme not found"를 리턴할 것이다.

더 복잡한 로직의 경우,

조건 내에서 더 복잡한 것을 해야할 때가 있다. 이 경우 Object key에 value값으로 함수를 전달할 수 있고 응답을 실행할 수 있다.

function calculate(nums1, nums2, action) {
  const actions = {
    add: (a, b) => a + b,
    subtract: (a, b) => a - b,
    multiply: (a, b) => a * b,
    divide: (a, b) => a / b,
  };
  return actions[action]?.(num1, num2) ?? "Calculation is not recognised";
}

?. optional chaining을 사용해 defined되었을 경우에만 응답을 실행할 수 있게 할 수 있다.
그렇지 않으면, default로 정한 string값을 리턴할 것이다.

복잡한 조건문의 경우 If-else 나 switch가 아닌 object literal로도 사용할 수 있겠구나-! 이 글을 통해 null 병합 연산자(nullish coalescing operator)도 알게 되어 좋았다. 개발할 때 써먹어야겠다 :)

참고 :https://betterprogramming.pub/dont-use-if-else-and-switch-in-javascript-use-object-literals-c54578566ba0

profile
Front-end Developer 👩🏻‍💻

2개의 댓글

comment-user-thumbnail
2022년 5월 14일

좋은 아이디어네요

답글 달기
comment-user-thumbnail
2023년 1월 9일

When the original language is something other than English, the best certified translation servicesis frequently utilized in coding. A professional association, such as the American Translators Association, regulates certified translation, a type of translation. The certification procedure entails confirming the translator's credentials, expertise, and ability to deliver precise and comprehensive translations.

답글 달기