by ryandrake · 4y ago · 0 comments
bool condition = /some really long boolean value with AND and OR clauses/;
if(condition); { /* some code to execute if TRUE */ }
Two advantages of doing it this way:1. It's much easier to notice that incorrect semicolon
2. Even if you don't, you can stick a breakpoint (or log) between when condition is set and when it is evaluated, to convince yourself it works.
3. All modern compilers will produce the exact same code as they produce with it mashed into the if()
bool subCondition1 = /* something kinda long */;
bool subCondition2 = /* something also kinda long */;
bool subCondition3 = /* something absurdly long */;
bool condition = (subCondition1 && subCondition2) || subCondition3;
if (condition) {
/* do something */
}
where, ideally, the sub conditions all have meaningful, relevant names that succinctly express what they were testing for.if(!condition) is a much better read and less prone to errors than trying to negate a long statement inside the if().
This pattern also eliminates duplication. I have fixed bugs in code where the same long if condition was duplicated several times within the same function (probably with cut and paste). This wastes cycles recalculating it each time and runs the risk of changing one of them without changing them all.
Your change also got me thinking of unit tests: at some point it becomes worthwhile to have dedicated tests on that condition, and that's often easiest by putting it in a static method, and that also improves readability.