Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 810
Archiac Coder Avatar asked Aug 09 '26 22:08

Archiac Coder


1 Answers

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();
}
like image 51
Boris Avatar answered Aug 12 '26 12:08

Boris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!