zoukankan      html  css  js  c++  java
  • 一种可能比 if-else / switch 更好的方式

    背景

    这两天做 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

    不熟悉的朋友, 可以去看一下文档: https://developer.mozilla.org

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

    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";
    }

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

    http://www.ssnd.com.cn 化妆品OEM代加工

    结论

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

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

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

  • 相关阅读:
    java 变量的初始化顺序
    Asp.net MVC3.0 入门指南 1.简介
    使用EnterpriseLibrary5实现数据的缓存(附完整代码下载)
    js showModalDialog 取得(访问)父窗体的语法
    Asp.net MVC3.0 入门指南 2.控制器Controller
    linq 之入门(一) O/R设计器的使用
    sql2000 示例数据库Northwind的 ER图、字段说明及使用Powerdesigner反向工程方法
    局域网共享文件win7系统
    远程桌面 不能粘贴文本 的解决办法
    解决vs2005控件事件为空白
  • 原文地址:https://www.cnblogs.com/xiaonian8/p/15012304.html
Copyright © 2011-2022 走看看