if A and B:
..
elif B:
..
vs if A and B:
..
elif A and not B:
..
I prefer flattening because enumeration makes it obvious what's different between the branches despite the code duplication.For example, three boolean conditions has 2^3 = 8 possible combinations. When nested this complexity is hidden but obviously apparent as a code smell when flattened.
It also echoes Python's ethos that flat is better than nested.
if( condition_a )
{
if( condition_b )
{
do_thing_a();
}
else
{
do_thing_b();
}
}
else
{
do_something_else();
}
Editor space is free, why not use it.The more lines that are visible on your screen, the less you have to keep in your working memory. Human memory is fragile, so you really don't want to rely on it.
I can only fit 51 lines vertically (damn widescreen laptop) so that one snippet fills a good 1/3 of my screen.
Personally I'd write that as
if (condition_a) {
if (condition_b) do_thing_a();
else do_thing_b();
}
else {
do_something_else();
}Sure if you only saw a few lines at a time, then this might be a problem. But you can see 51 on a laptop. This is enough for almost all cases. And you can scroll if you need to look up something. If you stumble upon a case of multiple if statement that span several screens then no style is going to help you see it in full. In that rare case you might see a little more, at the expense of all code ever becoming less readable (if we assume Allman is more readable for the sake of this argument of course).
If for some reason your code has more than, let's say >50% cases where something spans multiple screens and needs to be seen as a whole (code which should be refactored, but let's ignore that), then you might have an argument to use your style, in all other cases you're doing premature optimization of your coding style, so to speak.
However I also always comment nested logic chains with their intent in plain language. I have made bugs in going from intent->complex logic to often, and I found that writing comments at each fork greatly reduces these errors as well as the odds of missing an edge case.
e.g., I'd write "if(a) and not b" in plain English at the nested else statement, possibly followed by a "what & why" comment at the do_thing_b statement.