1

I am refactoring my code, I am using SonarQube, SonarRunner, JSHint to follow the best practices to check code complexity,quality and duplicate.

For normal if else if loop the complexity is high somewhere between 15 to 20 I need to reduce it to below 10 ho do I do that.

if( ..condition.. ){

}else if( ..condition.. ){

}else if( ..condition.. ){

}

like this I have around 15 to 20 conditions. Can any one suggest me how do I reduce the complexity?

1
  • Well to be honest if you have 20 if/else cases in your code you're probably doing something wrong Commented Mar 9, 2017 at 8:43

1 Answer 1

0

It depends on the context. If you have repeated business logic like

if(object.color === 'red'){
  runApple();
} else if (object.isRound){
  runApple();
} else if(object.isTasty){
  runApple();
}

then you can refactor all that into

function isApple(object){
  return object.color === "red" || object.isRound || object.isTasty;
}

if(isApple(object){
  runApple();
}

If the business logic to be run is completely different however, than you can try and group all the conditionals into some sort of function

e.g.

function isCondition1_2or3(){
  return isCondition1() || isCondition2() || isCondition3();
}

function exectue1_2or3(){
  if(isCondition1()){
    execute1();
  } else if (isCondition2()){
    execute2();
...
}

then you would refactor your large function to use the new function

if(isCondition1_2_or3()){
  execute1_2_or3()
} else if (...

The key is to find some sort of natural grouping in your business domain that represents the different conditions like in the previous example where an object being red or round or tasty means that the object is an apple.

However, if there really isn't a natural grouping representing the different conditionals. Its probably easier to tell your cyclomatic complexity checker to simply ignore that large function.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.