|
|
|
|
|
by blondin
2330 days ago
|
|
nested ifs work here too. i personally don't think cognitive overload is an issue because you are not composing all the conditions at once. in fact, each block should only care about one condition. but you make a good point. tbh, i have seen nested ifs used in video game programming a lot. and i came to the conclusion that it has to do with the else clause that the return early method doesn't provide. the else clause is always doing something because games are never supposed to fail... |
|
I'd also add that it's a good idea to break out complex condition checks to their own independent if statements on separate lines. I'd even go further and decompose the condition expression into individual boolean variables so that if you build in debug mode you have all the evaluated values held in variables for inspection. In release mode the variables should be compiled away.
There are some practical and aesthetic benefits that come from reducing nesting and breaking apart complex if conditions:
* less horizontal scrolling in your editor * no need to parse complex boolean expressions all stuffed into very few `if` statements * easier ability to step through code within a debugger and follow the execution logic more exactly * more distinct line numbers for crash dumps / stack traces to refer to in order to exactly identify which condition or evaluation is causing a failure
That last point is very beneficial when you hand your code off to someone else and they send you back a stack trace to investigate. Your code probably crashed at a complicated line of code full of boolean-combined expressions and any one of them could be at fault. All you know for sure is that something went wrong at that line number. No other hints given as to what went wrong or what the value of all the relevant variables on that line are.