🤔️ 一种可能比 if-else / switch 更好的方式

375 阅读2分钟

image.png

背景

这两天做 Code Review 的时候, 发现很多 if-else / switch 语句,并不是特别优雅。 在一些逻辑复杂的地方,看起来比较臃肿, 不是那么好读。

举个例子:

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

这样做看起来十分臃肿, 而且做了太多 lowercasedRhyme === 'xxx'的判断, 以后有一个新的分支, 都需要判断一次。

如果换成 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";
  }
}

情况有所改善, 但是依旧显得臃肿,我们只需要返回一个值。

遇到具有更复杂的功能时,也很容易错过 break声明, 造成错误。

再换一种方式:

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 的形式去取用数据, 最后用 ?? 最为兜底。

这里的 ??, 就是所谓的空位合并运算符 :

const foo = null ?? 'default string';
console.log(foo);
// expected output: "default string"

const baz = 0 ?? 42;
console.log(baz);
// expected output: 0

不熟悉的朋友, 可以去看一下文档: developer.mozilla.org/en-US/docs/…

如果遇到了更复杂一点的逻辑, 在适合的场景也可以用这种方式来做, 比如:

function calculate(num1, num2, 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";
}

有一点注意一下,这里我们同时用到了 ?.?? 操作符。

结论

今天讨论的这个问题,其实比较主观, 带有一定的个人偏好。

代码的可读性可维护性, 应该是我们都需要注意的。

今天的内容就这么多, 希望对大家有所帮助 :)