Reduce Complexity Of If Elseif Conditions
Solution 1:
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
.
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
functiontestFunc() {
var step = getModel('step');
var steps = {
1: function() {
this.editTask(); //calling some functionthis.updateStep(0);
returntrue;
},
2: function() {
this.initTask; //some other functionreturntrue;
},
3: function() {
this.name === 'add' ? this.add() : this.edit();
returntrue;
},
default: function() {
returnfalse;
}
};
var fn = steps[step] || steps.default;
returnfn();
}
Solution 2:
This will reduce your code complexity and makes more readable. You can decouple your condition into multiple function and attach that function in condition object. here I'm passing this in argument but you can use different approch. here I've also given value of this just for the shake of running example. copy and paste in your editor and try.
function meaningfulFuncName1() {
this.editTask(); //calling some functionthis.updateStep(0);
returntrue;
}
function meaningfulFuncName2() {
this.initTask; //some other functionreturntrue;
}
function meaningfulFuncName3(context) {
context.name === 'add' ? context.add() : context.edit();
returntrue;
}
function defaultCase() {
returnfalse;
}
function testFunc() {
this.name = 'add'const step = getModel('step')
conditionObject = {
1: meaningfulFuncName1,
2: meaningfulFuncName2,
3: meaningfulFuncName3,
default: defaultCase
}
return conditionObject[step](this);
}
Solution 3:
To me, changing it like this makes it less complex to understand. Although to some will be less readable. Also it is a little faster.
function testFunc() {
var step = getModel('step');
if(step==1){this.editTask(); this.updateStep(0); returntrue;}
if(step==2){this.initTask; returntrue;}
if(step==3){this.name==='add' ? this.add() : this.edit();returntrue;}
returnfalse;
}
Post a Comment for "Reduce Complexity Of If Elseif Conditions"