降低if elseif条件的复杂性 [英] reduce complexity of if elseif conditions

查看:56
本文介绍了降低if elseif条件的复杂性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果elseif条件下且环复杂性接近5,我有一个函数.我该如何降低它?

I have one function which is having if elseif conditions and the cyclomatic complexity is approaching 5. How do I reduce it?

function testFunc() {
    var step = getModel('step');
    if(step === 1) {
        this.resetTask(); //calling some function
        this.updateStep(0);
        return true;
    } else if(step === 2) {
        this.initTask; //some other function
        return true;
    } else if(step === 3) {
        this.name === 'add' ? this.add() : this.edit();
        return true;
    }
    return false;
}

尝试用开关盒代替,但没有帮助.

tried replacing with switch case but it didn't help.

推荐答案

非常简单的重构-删除您现在拥有的所有条件逻辑,并将每个片段作为单独的函数提取到映射中.由于您每次只执行一个分支,具体取决于 step ,因此您可以将该值作为键并获取需要执行的内容.然后,当没有与 step 相对应的内容时,您可以提供备用.

Very simple refactor - remove all conditional logic you have now and extract each piece as a separate function into a map. Since you only execute one branch each time, depending on step, you can make that value the key and fetch what needs to be executed. You can then provide a fallback for when there is nothing that corresponds to step.

现在圈复杂度为2,因为代码分支只存在一个位置-您是否找到了 step 的相应处理程序.另外,第3步中的分支现在是一个完全独立的函数,因此它不需要算作 testFunc

Now the cyclomatic complexity is 2, since there is only one place the code branches - either you find the corresponding handler for step or not. Also, the branching in step 3 is a completely separate function now, thus it doesn't need to count as part of testFunc

function testFunc() {
  var step = getModel('step');

  var steps = {
    1: function() {
      this.editTask(); //calling some function
      this.updateStep(0);
      return true;
    },
    2: function() {
      this.initTask; //some other function
      return true;
    },
    3: function() {
      this.name === 'add' ? this.add() : this.edit();
      return true;
    },
    default: function() { 
      return false; 
    }
  };

  var fn = steps[step] || steps.default;

  return fn();
}

这篇关于降低if elseif条件的复杂性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆