Cascading if-statements vs. boolean expressions
It's such a good feeling once you finally figured out the right combination to evaluate boolean state and you all put it in a method like this:
public boolean isComplicatedConditionTrue() {
return a < CONSTANT_1 && b * 5 > CONSTANT_6 && b < a....;
}
But how easy is this code to read? What are the drawbacks, how could you write it differently?
Let's see:
public boolean isComplicatedConditionTrue() {
if (a >= CONSTANT_1) {
return false;
}
if (b * 5 <= CONSTANT_6) {
return false;
}
if (b >= a) {
return false;
}
...
return true;
}
A drawback that jumps at you is the fact that it is more lines of code. But there are also benefits to it:
Although it goes against the clever programmer's pride to write code so inelegantly and verbosely, in my opinion it's easier to interpret the code when reading it. Think of the poor guy that has to maintain the boolean expression that took you 3 trials to figure out correctly.
You can easily debug this code and see where the the condition is not met and your debugger can easily step through each line.
Also, it is very easy to add logging statements into each branch to find out which values caused the expression to be false.
As to testing, I'm not sure how good coverage tools are right now when it comes to breaking down boolean expressions and mapping them back to source code, but this could would make their job easier too.
Currently, I'm heavily leaning towards preferring this style when I know I'm going to end up debugging this code at some point, and I can't really see a major drawback with it. But, what do you think?
Comments
I also prefer writing out the if statements.
Ever since I learned about type safe enums, I have been tempted to try to eliminate ifs whenever possible.