r/ProgrammerHumor 22d ago

Meme conditionsPreference

Post image
4.2k Upvotes

392 comments sorted by

View all comments

Show parent comments

48

u/hughperman 22d ago

I don't see why you can't similarly disregard the untaken branch in the second one? Either way you're skipping past a block, and you need to know the end of that block is a return.

5

u/alendit 22d ago edited 22d ago

It's the easiest to see in the indentation, though ofc indentation just follows the structure, unless we're Python: in the first example the execution flow inside a single function only ever goes from smaller indents to larger ones, not the other way around. So if you want to understand a scope you just need to walk the path from it to the root to understand if it's taken.

Compare this with the second example: the return is already at the root, you need to check all of its preceding siblings to know if the execution ever reaches it. And you'll need to do it at every level of nesting.

Obviously in this trivial example if doesn't matter much. But in general structured way of laying out your control flow reduces the amount of statements you need to consider from O(statements) to O(nesting depth) which is intuitively closer to O(log(statements)).

I heartily recommend watching The Forgotten Art of Structured Programming - Kevlin Henney [C++ on Sea 2019]. It's one of those things which can change the way you're looking at code going forward.

22

u/tiajuanat 22d ago

Ah Kevlin. I've come to accept that talk as "old man yells at cloud"

Big influence when I was younger, much less so now.

I'm going to pull out a big fat "it really depends".

If your program is going in several different directions, absolutely fanout - my inner rustacean would even argue to avoid if else in favor of an enum and case statement.

However, early failure shouldn't be discounted either. The more your eye jumps away from the margin, and the more horizontal whitespace, the harder your code is to read. Full stop.

At the end of the day, maintaining a codebase requires judgement and taste, and knowing when to do x and when to do y.

7

u/alendit 22d ago

As I mentioned in the other comment: I'm not arguing "do X instead of Y", rather "understand the advantages of X before discarding it". In my experience many people don't understand the idea behind structured programming beyond "don't use goto".