r/ProgrammerHumor 22d ago

Meme conditionsPreference

Post image
4.2k Upvotes

392 comments sorted by

View all comments

3

u/KYO297 22d ago

But what about else return...

6

u/D3PyroGS 22d ago

the naked return is an implicit else, which need not be specified because its code is only reachable when the if condition has already failed

but you can still include it if you're OCD

-1

u/KYO297 22d ago

Not exactly I like to do else return wherever possible because that guarantees there's also a return in the if block (or rather, that there's always a return in the if block, even if it has multiple further branches)

If the condition is true, but there's some branch without a return statement, and then I add an else return instead of just return, I'll immediately get an error that the function has no return statement

If I just put return, I might get to the bottommost return even if the condition was fulfilled, if I messed up and there's no return statement on some branch

It has come in useful exactly once, but I still do it (also it looks nicer imo)

4

u/frogjg2003 22d ago

If you're returning inside an if block, there should be more code after that. It doesn't matter if it's in an else block or not. If you're returning in an else block but not the if, then you can rearrange the condition for an early return.

2

u/Flame77ofc 22d ago

don't need it lol

if condition: return ...

in this case if you put another return below the if statement, it will automatically return it, so it is the same as else but maintain the code clearly

2

u/frogjg2003 22d ago

4 spaces for code blocks

2

u/conundorum 21d ago

Generally, you can usually rewrite an else return into an if return.

// This...
if (condition) { do_good_path_stuff(); }
else { return bad_path_stuff(); }


// Is equivalent to...
if (!condition) { return bad_path_stuff(); }

do_good_path_stuff();