I am new to programming, and am wondering if there is a correct way to order your control structure logic.
It seems more natural to check for the most likely case first, but I have the feeling that some control structures won’t work unless they check everything that’s false to arrive at something that’s true (logical deduction?)
It would be hard to adapt to this ‘negative’ view, I prefer a more positive outlook, presuming everything is true 🙂
In most situations, readability is more important than execution speed. I therefore try to optimize for ease of understanding, by using the following approach:
All ‘assertion’ checks are done up front. this guarantees that all erroneous cases are dealt with at the very start. this is especially important for null-pointer-checks, e.g.
if(arg == null){ throw new IllegalArgumentException(); // harsh (correct) } // or if(arg == null){ arg = ''; // forgiving (lazy) }Next, i try to check for 1 condition only in each if-statement. instead of
if(condition1 && condition2) { ... } else { ... }i generally prefer
if(condition1) { if(condition2) { ... } else { ... } } else { ... }This approach is easier for setting breakpoints, and it makes the logic more obvous.
I avoid negations; instead of
if(! condition) { ...a... } else { ...b... }things are better rearranged to
if(condition) { ...b... } else { ...a... }Finally, all methods that return a boolean result should have a ‘positive’ name that indicates what the results means:
boolean checkSomething(Something x){ ... } // bad -- whats the result? boolean isSomethingInvalid(Something x){ ... } // better, but ... boolean isSomethingValid(Something x){ ... } // best, no 'mental negation'