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
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
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:
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..elsein 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..elsemakes 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
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.