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.
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 aniforwhilestatement. 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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With