How to decrease cyclomatic complexity of the multiple conditions in if?

1k views Asked by At

I have been trying to learn how to reduce cyclomatic complexity. I have here 5 or more conditional checks inside a if statement e.g

if(something1() && something2() && something3() && something4() && something5()){
     doThatThing();
}else{
     doThisThing();
}

The cyclomatic complexity of the above snippet is 6 (5 condition +1 if). I know use of Enum and Chain of Responsibilty which is used to refactor multiple if else. But, here I have only 1 if else where conditions can be many.

How to refactor the above code to reduce cyclomatic complexity since in real scenario I may have a maximum of 7 conditions.

1

There are 1 answers

0
Boris On

According to Clean Code by Robert C. Martin, page 301 it's a general smell:

G28: Encapsulate Conditionals.
Boolean logic is hard enough to understand without having to see it in the context of an if or while statement. Extract functions that explain the intent of the conditional.
For example:

if (shouldBeDeleted(timer))

is preferable to

if (timer.hasExpired() && !timer.isRecurrent())

Like @tgdavies is suggesting extract a function:

if(shouldDoThatThing()) {
  doThatThing();
} else {
  doThisThing();
}

private boolean shouldDoThatThing() {
  return something1() && something2() && something3() && something4() && something5();
}