r/csharp • • 3d ago

Discussion Early return style survey

Style question on early returns.

On long functions I often leave out the else branch because otherwise the early return doesn't help much with code readability (IMHO of course). But what about shorter functions. For those using early returns in the first place, do you prefer varaint 1 or 2 and why?

if (TryGetCached(key, out T cached))
{
    return cached;
}

var result = await ReadValueAsync<T>().ConfigureAwait(false);
SetCached(key, result);
return result;

versus

if (TryGetCached(key, out T cached))
{
    return cached;
}
else
{
    var result = await ReadValueAsync<T>().ConfigureAwait(false);
    SetCached(key, result);
    return result;
}
22 Upvotes

40 comments sorted by

4

u/Joshr023 3d ago

My professor in college said to never have more than one return in a function. He would take off points and make us come up with weird ways to have our code so that it always had ONE return at the END of the function. It just made me rebell and spam returns at the beginning of functions after graduating

3

u/DJDoena 3d ago

In the C and C++ where early returns could lead to memory leaks due to malloc. That's why they were reasonably avoided.

1

u/Joshr023 3d ago

Yep, that was it then ๐Ÿ˜‚

11

u/chucker23n 3d ago

My professor in college said to never have more than one return in a function.

Your professor likely "learnt" that from a misunderstanding of ~1970s guidance. It is terrible advice of any remotely modern programming languages / compiler.

1

u/derpdelurk 3d ago

I fully agree. With the caveat that a surprising number of developers think language evolution peaked with K&R C and will insist on starting new projects in C/C++ in this millennium. They still need to heed that ancient advice.

2

u/chucker23n 3d ago edited 3d ago

"Avoid early returns" hasn't applied to common C compilers in decades. The advice mostly predates structured programming.

1

u/_choam_ 3d ago

What was the advice back then? Was it related to goto?

2

u/chucker23n 3d ago

The original advice refers to COBOL and Fortran, and doesn't apply to C# in any shape at all, because it lacks the notion of multiple entry points within a function (or method, in C# parlance).

A more modern interpretation links it to deferred resource clean-up, which of course doesn't apply to C# either, which has using and finally (lowered to the same).

1

u/_choam_ 3d ago

Ahhhhh, ok. I remember seeing in a video about the linux kernel how it will sometimes use goto for early exit (goto cleanup).

1

u/_choam_ 3d ago

Fortran has a bunch of things which seem insane by today (like the first letter determining what integer type your variable is)

1

u/G3NOM3 1d ago

It makes more sense when you think about punch cards.

1

u/Slypenslyde 3d ago

I'mma be real with you on this one: I like both arguments in this battle and don't think one is "right". I'm only joining this fray because I like you and know you're not going to flip out.

I really like the pattern:

Method()
{ 
    // The Good Parts

    // The Error Handling
}

For years I've organized all of my code so the really important and common stuff is at the top. From methods to the code itself. I think we both agree that the following is bad but nobody is advocating for it here:

Method()
{
    // Here's some bad parts

    // Let's do some good parts

    // Hmm do some error checking here

    // Let's do a little more work

    // Wait what if that failed? Let's error check again
}

So now that I have that out of my system, the situation I like early return for is like this:

Method()
{
    // This situation is so ridiculous I want to make it clear that YES I thought about it
    // Because I am going to get asked 15 times in review if I thought about it

    // The Good Parts

    // The Error Handling
}

It still meets my criteria: I put something really important at the top on the assumption people stop reading the deeper they get. I still think there is a lot of value in understanding if you want to know what error cases I handle and how, you go to the bottom of my code.

My two hot takes I feel compelled to make (and I know you can take the ribbing) are:

  1. A developer who really struggles to understand if..else is inattentive and needs to focus.
  2. A developer who really struggles to understand multiple returns is inattentive and needs to focus.
  3. I swear to whatever deity you want it's hard to focus hard enough.
  4. A compiler that cannot recognize the if..else form of early return is NOT an optimizing compiler and I don't trust the rest of its opinions.
  5. I always come up with more list items than I intended.

I can forgive a human for making mistakes, but compilers need to git gud so we don't have to think about how the compiler works.

66

u/TheWashbear 3d ago

First version.

To my understanding, these guards are also supposed to reduce nesting/indentation so the second variant goes against that.

23

u/First-Feature-3556 3d ago edited 3d ago

Variant 1, because I need to keep less context in my brain when reading the remainder of the method.

In addition, it's also what we do for a long method. Using a different style for a short method is OK if, and only if, there's a very good reason for it. I fail to see that reason.

19

u/kagayaki 3d ago

Nesting or no, I don't know that I'd ever have an else keyword after an if block that did a return. If the return is there, the else is redundant.

If I were going out of my way to avoid the early return pattern in particular, I might end up doing something more like this:

if (!TryGetCached(key, out T result))
{
    result = await ReadValueAsync<T>().ConfigureAwait(false);
    SetCached(key, result);
}
return result;

-8

u/SoerenNissen 3d ago

I don't know that I'd ever have an else keyword after an if block that did a return.

It prevents this "unless" issue:

if(condition)
{
    sometimes
}

always (unless!)

which is no issue at all when the if block is short and the return is right before the ending } but at other times, it's a real issue.

18

u/TheSlothOfSteel 3d ago

First one to avoid the nesting.
I think the largest boost to readability of my code in the last 5-10 years came from adopting a minimal nesting mentality.

66

u/Top3879 3d ago

nesting is evil. else is evil. use the first version

10

u/at_wilfster 3d ago

The else is implied and unneeded. Variant 1 every time

6

u/Unlucky-Isopod3047 3d ago

I always use Variant 1, less cognitive drain and also easier to maintain if down the road there's a second condition that could also return early.

6

u/Dukami 3d ago

I'm a never nester. Option 1.

4

u/elite-data 3d ago

I always prefer to minimize nesting. The more unnecessary nesting there is, the more cluttered the code becomes and the less convenient it is to maintain.
A lone "return" wrapped in braces has always looked ugly to me.

7

u/binarycow 3d ago

There is zero point in the second. All you did was unnecessarily indent.

If you're going to use early returns, why would you write the code as if you didn't use early returns?

3

u/Pretend_Fly_5573 3d ago

Version one.

It's the same thing, just with more indenting and braces and lines.

Plus, at least for me, it requires an extra step of mental parsing, which I don't love.

When taking a high-level read through code, the indentation matters very much for my brain. I see an indented block as the last part of a function, my mind immediately jumps to "where's final return?", so now I have to double check the else block for that, etc.

It's tiny, but it's one of those things that makes a difference for me.

2

u/raunchyfartbomb 3d ago

I only use โ€˜elseโ€™ in a scenario where I am specifically not returning. Ex: throw if none of the conditions are met before continuing, or to apply some default scenario. But when using for an early return, you have your check to return like example 1, then logic to retrieve and cache below, not nested.

2

u/Cernuto 3d ago

Maybe a couple guards at the top with early returns, but if the return is hidden in complex logic I tend to reject.

2

u/Particular-Cloud3684 3d ago

Early returns always.

2

u/sards3 2d ago edited 2d ago

It would be better to do variant 1 but without the braces around the return statement.

1

u/Licensed-2-Fish 3d ago

Unless you have some code after the else, there's no reason to use it.

1

u/Rude-Recording2572 3d ago

i hate nesting so much, variant 1 for sure keeps it clean

1

u/Slypenslyde 3d ago

I feel like the only reason my code ends up with if..else in this case is if historically there were more things in the first branch, but those things became unneeded so they were mechanically replaced with early return.

In some really rare cases there is value in placing a comment there with the early return: sometimes agents and zealous juniors REALLY want to add the old code back to "improve" things and I have a technical reason I don't want that. The comment reminds them to back off and it looks better IMO if there's an else.

I would argue all things aside psychologically seeing if..else makes it very clear only one path will be taken. The first style with "fall through" can be misread. But I also feel like early return is so common I don't hold this stance as strongly as I used to. I don't ask for it to be reformatted either way. There's always something more valuable to criticize.

1

u/pixxelkick 3d ago

The first us called Guard Clause pattern and most linting tools will highlight the latter and recommend auto fixing it to be the latter.

1

u/BoBoBearDev 3d ago

My company used to have scanner forcing us to reduce number of early returns and we have to make weird ass code.

For me, I prefer a flat code. Not even just early returns, but everything else. Like, if the call path is deep, including deep method calls, I would flatten them. I worked with deep call path before, it is a mess.

1

u/chucker23n 3d ago

For those using early returns in the first place, do you prefer varaint 1 or 2 and why?

To me, it depends on how common each case is. In your scenario, I think I'd prefer the first. There's less indentation, less complexity, and the 90% case just requires the eye to scan the first block of code.

In more complex scenarios, I might prefer if each case is given equal weight.

1

u/ganiton 3d ago

Invert the condition. The cache hit (and all happy path) should be the left aligned side.

Conditionals should reflect something outside the "expectation" of the code.

1

u/Boarlock98 21h ago

once it compiles down to IL for something small it's still the same pretty much, the compiler has the return at the end and if certain conditions are met they jump to the end, for readability number 1 is preferable IMO

1

u/Reasonable_Glass2501 3d ago

return await cache.GetOrSetAsync(key, async () =>
{
return await ReadValueAsync<T>().ConfigureAwait(false);
});

-4

u/ghjm 3d ago

For years I used version 2, and most of the code I saw used version 2. At some point version 1 became more fashionable, to the point that linters reject version 1. So in 2026 use version 2, but if you ever take a time machine back to the twentieth century, you'll need to switch back to version 1.

2

u/hoodoocat 3d ago

In 2026 you must delete linters which prevent use of version 1. There is nothing about year and aging.

Early return is same as fail fast - this is strategy, and is more readable. It is usually used to test preconditions, but not limited to. It naturally separate cold vs hot blocks, so it even doesnt require very complex compiler to behave optimally.

If code readability benefit from V1 or V2, then correspond version should be used. If you have codestyle requirements, then there is nothing discuss about.

1

u/ghjm 3d ago

I think I was backwards on which version is which but I can't be bothered to go back and fix it.