【问题标题】:How can I reduce cyclomatic complexity for the function如何降低函数的圈复杂度
【发布时间】:2020-02-13 21:23:57
【问题描述】:

我有这个复杂度大于 12 的函数。我试图降低它的复杂度。我四处搜索但找不到任何有用的东西是否可以降低这种复杂性? - 如果是这样,我该怎么做?

这里是函数

 function sea(name) {    +1
   if (name === 'sa') {         +1
      return 'SA';            +1
    } else if (name === 'uk') {    +1
      return 'UK';             +1
    } else if (name === 'northkorea') {   +1
      return 'NK';                 +1
    } else if (name === 'hongkong') {  +1
      return 'HK';                     +1
    } else {
      var rs = new RegExp(/\w);

      return name.replace(rs, function(up) {        +1
        return up.charAt(0);
      });
    }
  }```

【问题讨论】:

    标签: javascript sonarqube


    【解决方案1】:

    也许您可以使用一个对象来存储这些国家/地区的值(如字典),这样的事情应该可以完成:

    const countries = {
      usa: 'United-States',
      uk: 'United-Kingdom'
      // ... all other countries you want
    }
    
    function countryCaps(country) {
      if (countries[country]) {
        return countries[country];
      } else {
        // ... your regex replace function here
      }
    }
    
    const country = countryCaps('usa');
    
    console.log(country);

    【讨论】:

      【解决方案2】:

      你可以这样做:

      // Code refactor
      function look(country) {
        const countries = {
          sa: 'South Africa',
          uk: 'United-Kingdom',
          northkorea: 'North-Korea',
          au: 'Australia',
          hongkong: 'Hong-Kong'
        };
        const toUpperCaseFirstLetter = c => c.replace(new RegExp(/\w/), s => s.charAt(0).toUpperCase());
      
        return countries[country] || toUpperCaseFirstLetter(country);
      }
      
      // Testing:
      [
        'sa',
        'uk',
        'hongkong',
        'spain', // <-- not in the function's `countries` object
      ].forEach(c => console.log(look(c)));

      【讨论】:

        【解决方案3】:

        我认为没有必要更改此功能。它很好,易于阅读且易于测试。只需在此消息来自的任何工具中将其标记为误报即可。

        如果每个条件都有不同的变量,我的推理会完全不同。但是由于这个 if-then-else 序列就像一个简单的查表,所以它确实是错误的工具。它应该根据人类真正难以理解的内容来衡量复杂性。一个这样的例子是深度嵌套的 if 语句。

        【讨论】:

        • 这在 sonarqube 中不起作用,需要以某种方式将复杂度从 12 降低到 10
        • 登录 SonarQube,将问题标记为误报,完成。如果您没有这样做的权限,那就是组织错误。
        猜你喜欢
        • 1970-01-01
        • 2020-06-13
        • 2020-10-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多