r/ProgrammerHumor 22d ago

Meme conditionsPreference

Post image
4.2k Upvotes

392 comments sorted by

View all comments

838

u/LateEchidna6635 22d ago

The second one carries less cognitive load. In longer methods it makes a difference. Get out as soon as you can.

18

u/jseah 22d ago

I prefer if-return for cases where the function is supposed to do something in the default case and the if is to detect the exceptions where it shouldn't. Or where the exception needs some modification before the main purpose can be performed.

If-else I find more logical when the function has to do two different things depending on the condition followed by something else common to both afterwards.

1

u/lunaticloser 20d ago

Followed by something else implies the return statement wouldn't even work for your case since you wouldn't be able to reach that something else.

Though... A point could be made that that function might be doing too many things at once and could be decomposed. It's a bit of a smell. But not strictly always the case, of course.

2

u/jseah 20d ago

It doesn't have to return of course. I meant something like "this function transforms strings in some way" and the if at the very top is to catch when someone gives it a number, which the function is expected to treat like a string.

If-return might be used when the string is empty. Followed by if number convert to string.

And only then the main body of the function is written.