降低if-elseif条件的复杂性



我有一个函数,它具有if elseif条件,圈复杂度接近5。如何减少?

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

试着换成开关盒,但无济于事。

非常简单的重构-删除您现在拥有的所有条件逻辑,并将每个部分作为一个单独的函数提取到映射中。由于每次只执行一个分支,因此根据step,可以将该值作为关键字,并获取需要执行的内容。然后,您可以在没有与step相对应的内容时提供回退。

现在圈复杂度是2,因为代码只有一个分支位置——要么你找到了step的相应处理程序,要么你没有找到。此外,步骤3中的分支现在是一个完全独立的函数,因此它不需要算作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();
}

这将降低代码的复杂性并使其可读性更强。您可以将条件解耦为多个函数,并将该函数附加到条件对象中。我在这里把这个作为论据,但你可以用不同的方法。在这里,我也给出了这个值,只是为了运行示例的抖动。复制并粘贴到编辑器中,然后尝试。

function meaningfulFuncName1() {
this.editTask(); //calling some function
this.updateStep(0);
return true;
}
function meaningfulFuncName2() {
this.initTask; //some other function
return true;
}
function meaningfulFuncName3(context) {
context.name === 'add' ? context.add() : context.edit();
return true;
}
function defaultCase() {
return false;
}
function testFunc() {
this.name = 'add'
const step = getModel('step')
conditionObject = {
1: meaningfulFuncName1,
2: meaningfulFuncName2,
3: meaningfulFuncName3,
default: defaultCase
}
return conditionObject[step](this);
}

对我来说,这样更改它使理解变得不那么复杂。尽管对一些人来说可读性较差。而且速度稍微快一点。

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

最新更新