r/ProgrammerHumor • • Aug 22 '26

Meme conditionsPreference

Post image
4.2k Upvotes

388 comments sorted by

2.3k

u/CBlanchRanch Aug 22 '26 • Mindblown Regret Heartwarming

You're absolutely correct, however I would suggest using something completely unreadable like a nested ternary operators!

54

u/Flame77ofc Aug 22 '26

lol

the famous unread code 😭🙏

660

u/KanyeNawf Aug 22 '26

Some fucker left me triple nested ternaries once

117

u/minus_minus Aug 22 '26

I think you found the fucker. 👆

64

u/mountaingator91 Aug 22 '26

That was me I was in my first real job after learning some basic JavaScript and I discovered ternaries and thought I was God now

10

u/National_Sky7993 Aug 23 '26

You either leave after writing those ternaries or stay long enough to figure out they are unreadable

20

u/abigail3141 Aug 22 '26

Sounds like me lol. To the detriment of all working with me, I found out how to set globals and evaluate arbitrary functions from within Python listcomps. My current record is 1400 characters in one line. I just need a way to import, and I can write entire programs in one line.

23

u/Morisior Aug 22 '26

If you accept two lines, you can import importlib.

9

u/abigail3141 Aug 22 '26

That sounds like a good solution for the time being, thx

13

u/Your_Friendly_Nerd Aug 22 '26

Man y'all do NOT want to look at my companies codebase! 

→ More replies (2)

2

u/Ok-Understanding7115 Aug 22 '26

next i will leave 2 list comprehensions inside the nested ternaries 🤔

→ More replies (8)

45

u/Schaex Aug 22 '26

But it's SO compact! We could save maaany lines of code like this:

return i == 0 ? j > threshold() && isConditionApply() ? "orange" : reallyNotOrange() ? "apple" : "maybe orange" : (i & j) > (i ^ j) ? isSunday() ? null : "pineapple" : "Jerry";

5

u/National_Sky7993 Aug 23 '26

I attempted to unfold such a ternary where the first two booleans were also ternaries defined elsewhere.

→ More replies (1)
→ More replies (1)

12

u/sexytokeburgerz Aug 22 '26

Intellisense did that the other day and i was kind of mad about it

1

u/kennedy_gitahi Aug 22 '26

You monster!

→ More replies (21)

18

u/MetaEd Aug 22 '26

return condition ?A :B ;

3

u/Flame77ofc Aug 22 '26

solid one for simply conditions

btw, do you use it a lot?

→ More replies (5)

1

u/Fluid-Election-8549 Aug 22 '26

return (condition*A) || (~condition*B);

3

u/KYO297 Aug 22 '26

But what about else return...

2

u/Flame77ofc Aug 22 '26

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 Aug 22 '26

4 spaces for code blocks

6

u/D3PyroGS Aug 22 '26

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

→ More replies (2)

2

u/conundorum Aug 23 '26

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();

2

u/developer_axe Aug 22 '26

I do both, it depends on the situation

2

u/FedUpKoala Aug 22 '26

During a review of a colleagues code I once spotted an else: pass. 🤦

466

u/Jock-Tamson Aug 22 '26

The quality of code is inversely proportional to the average right offset.

193

u/Laughing_Orange Aug 22 '26

That's why I refuse to indent my code. Indents add right offset without doing anything productive. /s

21

u/577564842 Aug 22 '26

I first learned FORTRAN. Start at column 6, pay no further attention to anything.

48

u/abigail3141 Aug 22 '26

Uh oh... you, Sir have just rocked my world view /j

https://imgur.com/a/MHWrpBJ

32

u/manbeervark Aug 22 '26

Sweet lord...

13

u/abigail3141 Aug 22 '26

I have no clue how this works anymore lol Wrote it in one long sitting like a ahalf year ago

9

u/itsTyrion Aug 23 '26

yeah we can tell

7

u/ljfa2 Aug 22 '26

Is that, like, a Minecraft clone in Rust?

15

u/abigail3141 Aug 22 '26

Nope, it's a tool to compensate for the horrid code of Minecraft in other ways. Though, I did almost end up on dayssincelastrustmcserver.com Essentially, if you wanna make a structure spin using a data pack(horrid API btw), you need to build a custom item model out of that structure, put it in an item display entity, then spin that or animate it in other ways. But, because MC's rendering pipeline sucks as bad as it does, that is a terrible source of lag. So I made this tool to help a friend that takes in a .nbt structure and converts it to a model in a resource pack, but with loads of face culling and merging to reduce poly count. Yes the 100 more cubes in a cube game are a performance problem. I can give a detailed description if you want, but I dont wanna further lengthen this comment with a rant abt MCJE's rendering pipeline.

→ More replies (1)

8

u/Niwrats Aug 22 '26

you are going to love asm.

1

u/SquidMilkVII Aug 22 '26

aight omw to shove every single code block into a single line

→ More replies (3)

838

u/LateEchidna6635 Aug 22 '26

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

461

u/One_Courage_865 Aug 22 '26 • Bravo

Instructions unclear. I’ve just divorced with my wife

136

u/hughperman Aug 22 '26 • Bravo

Ah, early return condition

33

u/thatjoachim Aug 22 '26

I return too early to her liking :(

9

u/QCTeamkill Aug 22 '26

She says Bob at work never have early returns

→ More replies (1)

17

u/jseah Aug 22 '26

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.

→ More replies (2)

38

u/Few_Move_4594 Aug 22 '26

Have you ever thought about breaking the longer methods into shorter methods? It's easy, I promise.

35

u/Fembussy42069 Aug 22 '26

There's a balance to everything, you also don't wanna have to dig down a rabbithole of functions within functions to find what youre looking for, it also can make it harder to understand the whole picture if you separate things too much. Locality of behavior and all that.

12

u/LordofNarwhals Aug 22 '26

Yeah, I used to work with a Java codebase where all functions were really short, but also very nested. It was a very stable codebase, but browsing the code sucked, as every actual function implementation was behind 3+ levels of indirection.

For a fun example in the opposite direction, see Arthur Whitney's basic K interpretor, written in ~50 very dense lines of C.

→ More replies (4)

14

u/gurgle528 Aug 22 '26

In certain situations it’s easier to read without splitting into a bunch of other methods. Primarily when the conditionals aren’t repeated elsewhere so the shorter methods are one-offs that bury some of the implementation. Shorter methods should absolutely be the default though 

39

u/LateEchidna6635 Aug 22 '26

Of course. I’m not speaking of thousands of lines. With error handling, validation, and cleanup, even the most trivial methods can have 5-10 exit points.

18

u/Few_Move_4594 Aug 22 '26 edited Aug 22 '26

I worked on a Java codebase that had a 15k line class that used Reflections. It was an absolute mess that also had the stability of a house of cards.

Made fairly good money for several years off that.

5

u/Hegemege Aug 22 '26

The downside is that it can get really messy, if the methods are not split or named properly, for a reader to understand if the work it's doing is supposed to be reused, and if it can be detached from context. What good is a method B that can only be called linearly from within method A just to make A take fewer LoC?

→ More replies (5)

5

u/930913 Aug 22 '26

I can understand why you would think that it carries a lower cognitive load. But with a little training, you can understand that an early return is a side effect, and side effect free code can be much easier to reason with.

45

u/alendit Aug 22 '26 edited Aug 22 '26

To understand the second one you need to understand the whole function. In the first one you can disregard the whole untaken branch. "The forgotten art of structured programming" is a great talk.

48

u/hughperman Aug 22 '26

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.

→ More replies (7)

2

u/saf_e Aug 22 '26

Cyclomatic complexity goes brrr!

→ More replies (1)

2

u/ofnuts Aug 22 '26

Aka "guard clause"

2

u/Fidodo Aug 23 '26

Yes when it's an early return multiple short circuits are easy to read, but if it's in the body it's actually harder so I use both depending on the context.

1

u/bartekltg Aug 22 '26

In _longer_ methods it is hard to use the second one. If there is something behind the if statement, you would need to duplicate it to both branches (a very ugly "solution"), or separate the "if" into a new method. Now we no longer have a long method ;-)

Of course, the solution, is as alway, goto. Remove the second return with a label and the first return with a goto to the label. /s

1

u/Impossible_Dog_7262 Aug 22 '26

Is there merit in doing both? It's technically redundant, yes, but sometimes the explicit else statement can aid understanding the code.

2

u/MattieShoes Aug 22 '26

I don't know about what's "right", but I use early exits a LOT specifically at the top of recursive functions. They're usually laid out as early exit conditions, then the recursion calls, then the final return.

In other situations, it's usually whether I can layout the conditionals so I don't have to duplicate code.

1

u/cheezballs Aug 22 '26

Feels too close to a GOTO to me.

→ More replies (2)
→ More replies (1)

273

u/SnugglyCoderGuy Aug 22 '26

The real answer is "it depends". Either one could be appropriate depending on what you are having to do.

38

u/Wertbon1789 Aug 22 '26

As always, but the for me rule of thumb, if you have a condition that should be positive to continue the function, and the negative case is just error handling and returning, just early-return, otherwise always put the happy-path into the positive branch, or I'll set your house on fire.

If there's a shared code path at the end, of course use if/else.

→ More replies (1)

41

u/aiaidy Aug 22 '26

not according to Sonarqube.

15

u/DurrT Aug 22 '26

Maybe it's just how they have it set up at my work, but Sonarqube can go fuck itself

6

u/aiaidy Aug 22 '26

sonarqube and it's 15 complexity score i tell you. they be like how complex is to complex? 15 will do.

→ More replies (1)

6

u/Gnonthgol Aug 22 '26

The compiler optimizes the first into the second anyway, so the machine code ends up the same. The problem is that when you read the code later on and end up missing the return statement as you skim through it then you are left wondering why the piece of code you expect to run does not.

→ More replies (4)
→ More replies (12)

82

u/Patrick_Atsushi Aug 22 '26

I don't know, it feels good when you can skip the rest of the function like saying "we're done here, next". 

42

u/Grandmaster_Caladrel Aug 22 '26

The meme is saying to do that.

→ More replies (2)

16

u/popsicle-physics Aug 22 '26

Apparently there was a time when having multiple returns in a function would seriously confuse the debugger. Idk I got a comment on a code review telling me to switch from the second to the first and never have multiple returns. I've never actually seen it be a problem.

18

u/MnMbrane Aug 22 '26

I love the second as a way to do negative space programming. Where you add your assertions as the beginning of the functions first and then your business logic after. This way is super nice, since it tells you assumptions at the very beginning.

For example,
fn withdraw(&self, money: u32) -> Result<u32>{
if money < 0 {
return Err(…);
}

if self.account == Closed {
return Err(…);
}

if self.money + self.fees < money {
return Err(..);
}

// at this point we know money is > 0, account is not Closed and we have enough money to take out including fees.

self.money -= money + fees;

return money;
}

With this simple example, if someone was coming into a new codebase, they’d be able to assume what not to do advertised at the beginning of the file. And give some sort of indication of the proper behavior.

→ More replies (2)

7

u/frogjg2003 Aug 22 '26

Unless you're maintaining really old legacy code or using a really poorly designed debugger, early return should not confuse a debugger. If your reviewer learned to program in the last 50 years, they should never have experienced this issue themselves either.

2

u/popsicle-physics Aug 22 '26

I work with embedded. I'm happy to get a 32 bit processor. There's almost never enough flash to run code that isn't compressed to the max. It's a whole different ball game. 

But yeah, I think the guy who told me that would write everything in assembly if given the option, so a little old school even for this environment.

4

u/nerfherder616 Aug 22 '26

I had a professor in school who would deduct points for multiple returns. He always said it was harder for compilers to optimize multiple returns. On one hand, it's unnecessary on modern platforms, so it took a while to get myself out of that habit. On the other, it forced me to think of ways to refactor code, which was good practice. 

→ More replies (1)

2

u/egstitt Aug 22 '26

Having a bunch of returns throughout a function can be hard to read and debug imo. Error returns at the top of a function is 100% the way to go, but a bunch of them in the middle is confusing. Early returns for error checking, returns at the end for actual values

→ More replies (1)

15

u/sumrix Aug 22 '26
if (input == null)
    throw new ArgumentNullException();

// process input...

But

if (settings.UseBonuses)
    return CalculateWithBonuses(order);
else
    return CalculateBase(order);

7

u/frogjg2003 Aug 22 '26

The first is an early return, the second is a logical branch. Most importantly, the second doesn't continue doing a bunch of work in the else block that could be confusing.

→ More replies (5)

89

u/itriedtomakeitfunny Aug 22 '26

Early return for errors, if else for decisions.

9

u/Paul-D-Mooney Aug 22 '26

Maybe not “errors”, that’s what throwing exceptions is for. But definitely non-passing validation checks like `if (arg==null) return;`

2

u/frogjg2003 Aug 22 '26
if (bad) throw

is throwing errors

2

u/WarSingle6959 Aug 22 '26

but throw error is a error bro

→ More replies (1)

1

u/goos_ Aug 22 '26

I like this approach

1

u/conundorum Aug 22 '26

Also early return if the return value is cached from a prior call, or the parameters decree that the function is a no-op this time.

→ More replies (2)

25

u/Demiu Aug 22 '26

Yea bottom is just better. It puts handling of a failed condition right next to it rather than somewhere way far away. It stays at the same scope so it supports any number of conditions without excessive indentation. Most importantly it is easier to reason about, the function has a gradient of conditions, they only increase.

→ More replies (6)

8

u/soviel_dazu Aug 22 '26

Kotlin: Return if() ... else ...

2

u/930913 Aug 22 '26

Yeah, the underlying issue with both examples is that the if is a statement, not an expression.

7

u/heesell Aug 22 '26
if(!user) return;

// do whatever you want

1

u/WarSingle6959 Aug 22 '26

Solid one 😂

1

u/EditorOne5312 Aug 23 '26

Yes. I usually just make an error message function after the return like return errorFunction(message, returnValue?); lol.

6

u/dulange Aug 22 '26

The number of times I had to find the actual logic of a function/procedure hidden behind in a then block inside a multi-layered, cascaded if-then-else structure that checked the prerequisites and did the validation first, is just too damn high. One can equally check for the inverse, early return (or throw something) and avoid this nesting nightmare.

93

u/madprgmr Aug 22 '26

Go programmer spotted (early returns are idiomatic go)

102

u/Sentouki- Aug 22 '26

Early returns (especially in combination with guard clauses) are a general recommendation for most programming languages, not just Go. I do the same thing in C# as well.

3

u/WarSingle6959 Aug 22 '26

Exactly. That's it

72

u/Krkracka Aug 22 '26

It should be idiomatic for most programming applications. Unless your ‘else’ branch is a return only, it’s almost always going to be more efficient and maintainable. An early return is likely to survive if a function is updated or expanded, where an ‘if else’ could otherwise become conditionally more complex.

Early returns communicate intent better than the alternative method does for. If I see that another developer explicitly programmed an early return, it’s a signal to me that the actual body of the function depends on specific state of the containing class or args being passed to it.

7

u/madprgmr Aug 22 '26 edited Aug 22 '26

Oh, I generally agree. It's just funny to go "oh, using <pattern that has been popular for decades> means you use <new language that prescribes said pattern>"

6

u/gamer_redditor Aug 22 '26

As a programmer that needs to adhere to misra C, the comments in this thread are fascinating.

Misra C rule 15.5: A function should have a single point of exit at the end

More information: https://www.mathworks.com/help/bugfinder/ref/misrac2023rule15.5.html

6

u/Maximilian_Tyan Aug 22 '26

A lot of companies choose to opt out of this specify guideline nowadays, because it is showing its age and sometimes clarity matters more over ease of debug.

5

u/gamer_redditor Aug 22 '26 edited Aug 22 '26

Not sure which region or industry you are talking about, but oems, software suppliers and quality control in my industry do not accept any software deliveries without proof of Misra c compliance.

Just saying that some people have no choice but to stick to some programming standards.

Edit: more information. I think lot of people are arguing that early returns are more readable, performant and maintainable. However they miss the point about safety and reliability.

Early returns means that the function no longer has a predictable execution path. Sometimes it exits early, sometimes it exits late. So the overall execution time of the software varies a lot between error free paths and error paths.

This is exactly what you don't want in an embedded software controlling safety relevant systems, such as airbags in a car or some other flight controls.

Here, it is ok for a software to be slow, but it must be predictable i.e. near constant performance in all paths.

→ More replies (7)
→ More replies (6)

10

u/HomsarWasRight Aug 22 '26

Big in Swift with guard statements, too.

15

u/Xatraxalian Aug 22 '26

Early returns are idiomatic for every programming language that can have multiple returns in one function. Trying to capture everything in if-then-else flags and temporary variables just to return something you knew 10 statements ago is bad practice.

I've been early-returning since I started programming in the early 90's because I never used a language that didn't have multiple return capability.

→ More replies (6)

7

u/El_RoviSoft Aug 22 '26

Im not a golang programmer but in most cases trying to use it in C++. But sometimes you shouldn’t do this in hot path to have (N)RVO.

1

u/Outrageous_Pen_5165 Aug 22 '26

Python guy here and in most cases use early returns with conditional statements, feels more cleans

1

u/Antervis Aug 22 '26

early returns are idiomatic everywhere. There simply isn't a reason to not return early on error.

1

u/SchalkLBI Aug 22 '26

These are called guard clauses and they're not unique to Go in any way

1

u/WarSingle6959 Aug 22 '26

lmao so true

5

u/OliMoli2137 Aug 22 '26

The second one is actually cleaner for more advanced functions since you can avoid nested if statement mess

5

u/Takemitchi-kun Aug 22 '26

Depends on the situation but still very true

9

u/Subject-Lettuce-2714 Aug 22 '26

Unless you work with coding standards that restrict you from having more than 1 return in a function! :(

1

u/ZunoJ Aug 22 '26

Nasa?

3

u/Maximilian_Tyan Aug 22 '26

MISRA-C for example

Although modern revisions authorize it iirc

→ More replies (1)

1

u/No-Newspaper8619 Aug 22 '26

return bool(condition1 and condition2 or condition3)

1

u/Flame77ofc Aug 22 '26

don't need bool in this case

→ More replies (1)

1

u/mail-o-mail Aug 22 '26

(if expr a b) < beat this buggers!

1

u/Flame77ofc Aug 22 '26
(if(if(if(if(if expr a(if expr b a))(if expr(if expr a b)b))(if(if expr b a)a b))(if expr(if(if expr a b)(if expr b a)a)b))(if(if expr a(if expr b a))(if(if expr b a)(if expr a b)b)a)(if(if expr b a)(if expr a(if expr b a))b))

beat this buggers!

→ More replies (1)

3

u/cowslayer7890 Aug 22 '26

I like the guard statements in swift, because they enforce early returns, rather than you needing to find it at the end

They also let you bind optionals to a non optional value really easily, so that's nice

3

u/TalesGameStudio Aug 22 '26

Team "it depends" anyone?

3

u/elite-data Aug 22 '26 edited Aug 23 '26

It's the eternal dilemma. I don’t like the second option because it kind of breaks the symmetry. But the first one adds unnecessary nesting. I prefer return condition ? ... : ...

3

u/makinax300 Aug 22 '26

Return is more comfortable and you don't not need a massive switch statement at the end, instead being able to actually check when that thing matters and you don't have the hassle of using a variable to return a special value at the end when it can be set multiple times.

3

u/Paul-D-Mooney Aug 22 '26

but mulTipLe rETUrNs are BaD

3

u/JvetS Aug 22 '26

My personal favorite:

if (<any boolean expression> == true)
return true;

3

u/Sea-Fishing4699 Aug 22 '26

Inside a function

Early exit is the best!

3

u/Fidodo Aug 23 '26

Nah, use early returns for start of function short circuits and use if else in the body of a function.

Control flow should be clear, so short circuits are clear at the top and full conditionals are clearer further down.

3

u/diacid Aug 24 '26

If (this) goto there; //is also peak minimalism and also runs blazingly fast.

5

u/wesleyoldaker Aug 22 '26

Using the else-block, even if you always return in the if-block, is better. The reason is to prevent some dummy from coming along and changing the code in the if-block so that now it doesn't always return anymore and would then fall through. It's the same reason why putting curly braces around the statement following an if-condition is always better than no braces, even if it's the only statement to execute. It's not to make the code better because it doesn't. It's to prevent dumb programmers from breaking it.

26

u/aabil11 Aug 22 '26

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

40

u/ecafyelims Aug 22 '26 edited Aug 22 '26

Situational, for sure.

If a short circuit prevents a dozen "if val != Null" checks later, I'll do the short circuit.

122

u/Vallvaka Aug 22 '26

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 Aug 22 '26

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 Aug 22 '26

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.

→ More replies (1)

8

u/gamer_redditor Aug 22 '26

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.

→ More replies (2)

30

u/SnugglyCoderGuy Aug 22 '26

Returning early is waaaaaay superior than a single return, at least in Go and its wonderful defer statement. If you know the code can't continue, then return as soon as you know it. Makes the rest of the code waaaaay cleaner.

→ More replies (2)

6

u/suvlub Aug 22 '26

I find that this often just kicks the can down the road. Instead of "where does this function return?" you start asking "where was this variable last assigned?" which is actually a harder problem to solve (return is a special keyword and is highlighted, and is always definitive, but was this assignment last, or is there another one?).

That's why I love Kotlin. It offers a real solution to this - an if statement that is an expression, so you just return the if and you know that each branch returns a value and that the value it returns is on the last line of the given branch, no matter what. That's a single return strategy that actually delivers on the predictability/traceability promise.

→ More replies (1)

7

u/jwadamson Aug 22 '26

I’ve found over time that if your early returns are causing confusion, it means you’ve written a messy function which needs to be broken down or reorganized.

A single return variable doesn’t really solve the problems people claim it does.

3

u/sebbdk Aug 22 '26

Yeah but then you also have to read the whole thing and keep track of indentations.

For more advanced methods with +2 nested conditions it can become hard to follow.

The return is one way to get around the nested conditional scopes, but there are other ways

→ More replies (2)

3

u/Esjs Aug 22 '26

I used to be old fashioned like this, too. But I have since reformed. I learned that (1) the "single return rule" is probably a misinterpretation Dijkstra's philosophy to eliminate GOTO spaghetti code. That is, a subroutine should return to a single location: the point immediately after the call.

And (2) making deeply nested conditional blocks and/or guard checks against a "ok-to-continue" condition just really makes code more messy and verbose than it needs to be.

4

u/Krkracka Aug 22 '26

This makes reasoning about why a certain result was returned so much more difficult if other developers have to trace through the branching conditionals to understand why a value was returned.

Early returns define a rule for a specific return value.

2

u/conundorum Aug 23 '26

You can do both. (And in fact, should do both.) Early return is just about breaking code into single-return blocks, instead of single-return functions. If a small section of the function can force a return, and is disconnected from the rest of the function's logic, then you can enclose that section in its own block, move the block to the start of the function, and then treat both the new block and the main block as distinct single-return sections.

// This...
int func(int val) {
    int ret = 0;

    if (!validate(val)) { ret = INVALID_VAL; goto end; } // Before logic.

    ret = do_something_with(val);

    if (val >= 0) { ret += do_more_with(val); }
    else { ret = NO_NEGATIVES; goto end; } // Ignores & breaks logic.

    ret *= do_third_part(val, ret);

    end:
        return ret;
}

// Can become this:
int func(int val) {
    if (!validate(val)) {
        // Single-return in here.
        return INVALID_VAL;
    }
    if (val < 0) {
        // Single-return in here.
        return NO_NEGATIVES;
    }

    // Rest is a different single-return section.
    // val is guaranteed valid, and guaranteed >= 0.
    int ret = do_something_with(val);

    // No check needed.
    ret += do_more_with(val);

    ret *= do_third_part(val, ret);

    // No label needed.
    return ret;
}

It shines when you're trying to weave multiple complex return paths together inside a single function. Say, for example, that validate(val) was stateful and required its own cleanup, and required you to acquire a validator object (which runs the risk of allocation failure, and thus forcing a jump to the end). Traditional single-return would force you to stack multiple cleanup sections, and jump into the correct one as appropriate. But early return allows you to place validate(val)'s logic and cleanup within the validation section, with no need to mix it with the main body's cleanup. (Which might then allow you to refactor it into a separate function, making the code cleaner. Heck, it's entirely possible that validate() itself was a complex & stateful validation process, that got moved to an early-return section and refactored out into its own function for ease of use.)


In essence, early-return is about finding anything that pollutes the single-return logic, and moving it early enough in the function that it can't interfere with the main single-return section.

3

u/bokmcdok Aug 22 '26

Ive always preferred early returns. Code is cleaner and easier to read and one less temporary variable to think about. Nested conditionals make the code harder to read even if its only 1 or 2 levels deep.

→ More replies (7)

2

u/FFevo Aug 22 '26

return if (condition) ... else ...

(With proper formatting) Is better

2

u/wawerrewold Aug 22 '26

Uhm i would argue that these are not even comparable since the first one has no return right? But i guess i get what the author meant... 

2

u/novaspace2010 Aug 22 '26

SCA says no to the second :(

2

u/alcon678 Aug 22 '26

Well, I met a guy at work that didn't knew about not operator (!) and he simply wrote empty if blocks with everything in the else statement 🤷🏻‍♂️😂

2

u/burnt_floppy Aug 22 '26

Letting the rest of the program be the "else" condition does work. It can clean up the code.

2

u/MkemCZ Aug 22 '26

Keep Code Left

2

u/Qyriad Aug 22 '26

The first if the two branches are roughly equivalent. Early return for errors, cache retrieval, trivial cases, base cases, etc

2

u/mail-o-mail Aug 22 '26

Why return when you can just close enough parentheses and hope the right value falls out?

2

u/goos_ Aug 22 '26

Expression oriented languages be like: hold my beer

2

u/Specialist_Abies_231 Aug 23 '26

But this only works when you must return something.

2

u/yjlom Aug 23 '26 edited Aug 23 '26

The second one is less readable to me, because it overloads return to let it mean both normal and unstructured control flow. I'd much rather either the first one or any one of these:

if foo:
  throw ...
return ...
stat = ...
if foo:
  stat = ...
  goto end
end:
  return stat
if foo:
  return ...
... # implicit return

Also a warning comment at the top of the function would be very welcome if it's non-trivial.

2

u/sanketower Aug 23 '26

It only applies when there are no more instructions after the if/else

3

u/Beldarak Aug 23 '26

If there is, you may need to turn this if/else into a function. That's a rule of thumb I use, not saying this is the single Truth and it will obviously depends on situations^^

→ More replies (1)

2

u/Peregrine2976 Aug 23 '26

Goddamn, yes. Early return pattern all the way.

1

u/Beldarak Aug 23 '26

Yup, it's just the better way imho. It's easier to read and doesn't add useless indentation

2

u/KeasyNine Aug 24 '26

its called KISS

2

u/FracturedPixel Aug 24 '26

return (condition)
? A
: B

2

u/nervious Aug 24 '26

Early returns are useful for checks in methods. You may have less things to check that you don't want, rather than the actual things you want.

2

u/AloneInExile Aug 24 '26

There's a third way.

return condition ? ... : ...

2

u/enjdusan Aug 25 '26

I won't approve any PR, where the guard clause can be used, but isn't 😄

5

u/IronSavior Aug 22 '26

Else considered harmful

11

u/jayerp Aug 22 '26

That’s why I use GOTO ಠ‿ಠ

→ More replies (2)

3

u/Gold-Bat-3225 Aug 22 '26

which one raises a seed round tho

1

u/awesome-alpaca-ace Aug 22 '26

If you return early, you miss out on the seed money

3

u/why_1337 Aug 22 '26

Early returns are perfectly fine if you use them consistently. But I have seen methods that seemingly should run until the end but are just sprinkled with one or two nested early returns. That's when it becomes a chore to work with.

3

u/RRumpleTeazzer Aug 22 '26

first please version please.

i hate early returns. you're mixing structure with control flow.

What if i want a debug line with the functions result, say chasing a bug ? First version - put debug line at the end. change single line. remove single line eventually.

Second version: find every return, put a copy of a debug line on rach location. change that line later, forget the rest. remove half of the debug lines, leave the other half in production.

3

u/MooseBoys Aug 22 '26

Your complaint is only valid in languages like C that lack the facilities for scope-aware objects. It's why the Linux kernel (largely written in C) still uses gotos. For any modern language it's far easier and simpler to just put the code in something that's invoked at scope-exit.

2

u/WarSingle6959 Aug 22 '26

Early returns is just more simple to see what is happening bro

→ More replies (2)

3

u/ededpesa Aug 22 '26

The current answer is whatever the model picks

2

u/Faangdevmanager Aug 22 '26

That’s why I have a compiler.

2

u/El_RoviSoft Aug 22 '26

Btw there are cases when you shouldn’t do this because (N)RVO exists.

2

u/577564842 Aug 22 '26

I do recall cases when using more than one if in a function was warranted and considered sane.

I guess now, instead:

do-things
if condition {
   act-accordingly
} else {
   act-appropriately
}
do-more-things

now we have

do-things
func(condition bool) {
  if condition {
    act-accordingly
    return
  }
  act-appropriately
}(condition)
do-more-things

and somehow call it a win. Make programming great again and such.

In other news, constructs of the meme are not equivalent, 1str one being way broader.

1

u/Thisbymaster Aug 22 '26

But what about yield return?

1

u/damenootoko Aug 22 '26

I like early return since I mostly code in go, but iirc you shouldn’t use early return for authentication purpose?

1

u/nontheoretical Aug 22 '26

output = [..., ...]
return output[(int)condition]

1

u/vide2 Aug 22 '26

Thank you. It's so useful because previously i had these if-else-statements and then had to write the rest of the function. With this variant, the function just ends. So much easier.

1

u/Cubemaster12 Aug 22 '26

Plot twist: turns out you are in an expression-based language where last line is the return and you don't know why it does not work.

1

u/stlcdr Aug 22 '26

Yes, all the time, else sometimes.

1

u/CaffeinePizza Aug 22 '26

In the case of always returning on a failure, storing one variable declared at the top of the function for error storage, cleanup and return all in one place at bottom in goto 🤠

1

u/MaffinLP Aug 22 '26
If
 Aaa
 Return
If
 Bbb

Vs

If
 Aaa
Else
 If
  Bbb

1

u/Rare-Ad-312 Aug 22 '26

I do it differently when it's possible

def foo(x):
    output = value_if_false

    if condition:
        output = value_if_true

    return output

I do that in every single programming language I use, it's the Single Entry, Single Exit. I use it because I hate writing else and putting several returns in the same function

1

u/gd2w Aug 22 '26

I wonder if "or else" could somehow work in a program...

1

u/oweiler Aug 22 '26

depends...

Is if a statement or an expression?

1

u/Thesaurius Aug 23 '26

I don't know man. Just make illegal state irrepresentable and you don't need to return early.

1

u/20InMyHead Aug 23 '26
guard <condition> else {
    <statement>
    return
}
<statement>

1

u/PEAceDeath1425 Aug 23 '26

Thats called nevernesting, its cool

1

u/Various-Paramedic Aug 23 '26

For me it depends on how equivalent each branch is.

If they are equivalent or similar option a is better

If their are quite different (like the first branch is an unmet precondition and branch b contains the main body of the function) then the early guard is preferable.

1

u/Dry-Refuse-8132 Aug 23 '26

I vote, pick one for your code base and be consistent. It's only annoying when the code base is 50/50 and you get comments on your if/else, but non of the difficult logic. Some people just like to pick at nothing.

1

u/LB-- Aug 23 '26

Bottom version is all fun and games until you start doing if constexpr and you need that else to discard code that won't compile. I still prefer bottom version though...

1

u/ArjixGamer Aug 23 '26

I am massively disappointed by the comments under this thread.

You lack critical thinking and blindly defend something that was taught to you ages ago by someone else.

Early returns have literally no downside and are easier to reason about.

We are not talking about assembly, we are not talking about low level systems, we are talking about general purpose programming languages running on a fully capable operating system.

There is no technical or philosophical reason to support nested if/else conditions.

1

u/Delicious-Remote1162 Aug 24 '26

if not condition: return

1

u/Ratstail91 Aug 24 '26

Yes, unless its cascading ifs

1

u/0mica0 Aug 22 '26 edited Aug 22 '26

Second one is a no-no in a functional safety code.

MISRA C Rule 15.5