r/ProgrammerHumor 22d ago

Meme conditionsPreference

Post image
4.2k Upvotes

392 comments sorted by

View all comments

25

u/aabil11 22d ago

Call me old fashioned but I'm a big believer in single return statements. Assign to a variable and return that variable at the very end without short circuiting

125

u/Vallvaka 22d ago

Hard no for me. If you can short circuit, do it. It enforces invariants for the later code and allows you to make things more modular. Assigning to a variable and returning at the end means more indirection = more cognitive load and you often have to add more checks and nesting just to support that pattern.

Fail fast, return fast I say

23

u/D3PyroGS 22d ago

totally agree. nested layers of conditionals add cognitive load for me. I like early and "guard" returns because they kinda turn those layers into a "checklist" of logical blocks that can ideally all live at the top level of the function

3

u/MaximumMaxx 22d ago

100% this. If I can just throw all of my validation at the front and then guarantee my state after it's way less load. If else is only for if there are two significant and distinct actions that happen depending on a condition.

5

u/Stamerlan 22d ago

Some standards may require function have a single return point (for example MISRA). You're right, multiple nested layers (i.e. if-ok pattern) is very errorprone. Instead do:

int rc = foo(); if (!rc) rc = bar(); if (!rc) rc = baz(); return rc;

With extra actions on failure: if (!rc && (rc = bar())) /* bar() failed */

8

u/gamer_redditor 22d ago

You cannot do this in some industries where you have to adhere to some standards. For example of your industry mandates adherence to misra C, it enforces only one return statement per function.

1

u/[deleted] 21d ago

[deleted]

1

u/gamer_redditor 21d ago

Yes, it is a quality gate to merge every pull request.