Hacker Newsnew | past | comments | ask | show | jobs | submit | bboygravity's commentslogin

Why is "no early returns" not a good rule?

I do early returns in code I write, but ONLY because everybody seems to do it. I prefer stuff to be in predictable places: variables at the top, return at the end. Simpler? Delphi/Pascal style.


Early returns makes the code more linear, reduces conditional/indent depth, and in some cases makes the code faster. In short, it often makes code simpler. The “no early returns” is a soft version of “no gotos”. There are cases where it is not possible to produce good code while following those heuristics. A software engineer should strive to produce the best possible code, not rigidly follow heuristics even when they don’t make sense.

There is an element of taste. Don’t create random early returns if it doesn’t improve the code. But there are many, many cases where it makes the code much more readable and maintainable.


The "no early returns" rule came about because was a good rule in context, specifically C and FORTRAN code before roughly 1990. It was part of "structured programming", contemporary to "Go To Statement Considered Harmful", Dijkstra, 1968. And it became received wisdom - i.e. a rule that people follow without close examination.

For example of the rule, a function might allocate, do something and then de-allocate again at the end of the block. A second exit point makes it easy to miss that de-allocation, and so introduce memory leaks that only happen sometimes. The code is harder to reason about and the bugs harder to find.

source:

> A problem with early exit is that cleanup statements might not be executed. ... Cleanup must be done at each return site, which is brittle and can easily result in bugs.

https://en.wikipedia.org/wiki/Structured_programming#Early_r...

About 90% of us will now be thinking "but that issue doesn't apply to me at all in $ModernLang. We have GC, using (x) {} blocks, try-finally, or we have deterministic finalisation, etc."

And they're correct. In most modern languages it's fine. The "no early returns" rule does not apply to Java, TypeScript, C#, Rust, Python, etc. Because these languages specifically made early return habitable.

The meta-rule is that some rules persist past the point when they were useful. Understand what a rule is for and then you can say when it applies at all. Rules without reasons make this harder. Some rules have lasted: we typically don't use goto at all any more, just structured wrappers of it such as if-else and foreach


> And they're correct. In most modern languages it's fine. The "no early returns" rule does not apply to Java, TypeScript, C#, Rust, Python, etc. Because these languages specifically made early return habitable.

Early return is perfectly manageable in C as long as you aren't paranoid about function inlining. You just have a wrapper that does unconditional setup, passes the acquired resources to a worker, and unconditionally cleans up. Then the worker can return whenever it likes, and you don't need any gotos either.


> In C, you just have a wrapper that does unconditional setup, passes the acquired resources to a worker, and unconditionally cleans up. Then the worker can return whenever it like

Right, so you allow early return only in functions that do not have any setup and clean-up - where it's safe. Something like "pure" functions. And you describe a way to extract such functions from others.


I remember having this argument with my professor at the school, who insisted that a function should have only one "return" clause at the very end. Even as I tried, I could not get him to explain why this would be valuable and how does this produce better code, so I'm interested on hearing your take on this?

It helps prevent bugs with state. The apple login bypass bug comes to mind.

Basically, you have code in an "if" statement, and if you return early in that if statement, you might have code that you needed to run, but didnt.

Forcing devs to only "return once" encourages the dev to think through any stateful code that may be left in an intermediate state.

In practice, at my shop, we permit early returns for trivial things at the top of a function, otherwise only one return at the bottom. That seems to be the best of both worlds for this particular rule.


> The apple login bypass bug comes to mind.

I think you're talking about this "goto fail" bug?

https://teamscale.com/blog/en/news/blog/gotofail

> In practice, at my shop, we permit early returns for trivial things

Are you also writing C or similar? If so, then this rule is relevant.

In modern languages, there are language constructs to aid the cleanup on exit, such as using(resource) {} or try {} finally {} It really does depend on if these conveniences are available or not.

For the rest of us, the opposite of "no early return" is to choose early return only sometime - in cases where results in better code, e.g. shorter, less indented and unlikely to cause issues due to failure to cleanup on exit. And avoid it where it might be problematic. In other words, to taste.

> Kent Beck, Martin Fowler, and co-authors have argued in their refactoring books that nested conditionals may be harder to understand than a certain type of flatter structure using multiple exits predicated by guard clauses. Their 2009 book flatly states that "one exit point is really not a useful rule. Clarity is the key principle: If the method is clearer with one exit point, use one exit point; otherwise don’t".

https://en.wikipedia.org/wiki/Structured_programming#Early_e...

this thinking is quite different to say, 25 years earlier than that, and IMHO the programming language constructs available play a big role.


The rule of thumb I use is to only have one return after modifying state that will persist outside the function call.

Thank you!

For me it's mostly about indentation / scope depth. So I prefer to have some early exits with precondition checks at the beginning, these are things I don't have to worry about afterwards and I can start with the rest at indentation level "0". The "real" result is at the end.

> Why is "no early returns" not a good rule?

It might be a good guideline.

Its not a good rule because slavishly following results in harder to follow code written to adhere to it.


Because good code checks pre conditions and returns early if they are not met.

I've been in towns in Mexico where the kids ONLY speak a Mayan language. No Spanish or English.

I asked for directions and just got blank stares until someone who spoke Spanish in the village explained, lol.


Where for example? I'm curious!


Meaningless. You can replace socialist by capitalist and it would be equally meaningless.

The correct word is democracy. The people (or "workers") having a say or not has nothing to do with socialism or capitalism IMO.


Those who hold the money hold the power. Is rule by billionaires really democratic? Have you seen how easily they are wiping their asses with our democracy now that it’s convenient?


Are you ignoring the fact that they actually have the support of people?


That’s a stretch. The billionaires weren’t democratically elected to anything, not even by our system where money buys influence and propaganda. No, they’re just rich.


No I am saying that the people wiping their asses with democracy have the support of the people and billionaires which suggests its not just billionaires overriding what people want. People have chosen this.


Roughly one third of eligible voters voted for Trump, one third for Harris, and one third abstained, presumably because they felt neither candidate represented them. In a government where money buys power that’s not a totally unreasonable take. Democrats for their part have blamed voters for their supposed stupidity - not themselves for failing to field an appealing candidate. They could have won on a left populist platform to counter Trump’s right populism (left wing populism has proven itself popular), but leftwing populism doesn’t sit well with Democrat financiers. Oligarchs like rightwing populism though. Populism (left and right) is itself an expression of the growing distrust people have toward their institutions and the sense people have of being squeezed economically. The ultra-wealthy are successfully capitalizing on this by using rightwing populism to dismantle democracy and consolidate power.


I dont see how you could blame anyone except the voters. No sane person can look at both platforms and struggle to make a choice.


The wealthy wouldn’t spend their riches on propaganda if it weren’t effective. Trumpism appeals to primal emotions around family, religion, pride, safety, belonging.

Social media is tribalism and echo chambers. The “other side” appears ‘insane’ to each side when there’s no empathy.


Well he did try out, how should I say that, a different, bigger type of democracy.


I don't understand the downvotes - parent's right. All regimes today like to trumpet themselves as (exceedingly!!) democratic, the question is: are they? In my estimation, overall, communist countries have done significantly worse in this department. And yes, rule by the many people is the definition of democracy.


"rule by the many people is the definition of democracy"

Well with elections we have a "rule by a few".

Wondering if elections could not be replaced by an app.


AI progress has slowed down?! By what metric?

Quite the statement for anybody who follows developments (without excluding xAI).


"make speculative statements"

isn't this 99 percent of modern infotainment "journalism" though? making speculative statements, omitting and lying..


What are the chances that Signal is an op ran by the NSA?



A single malicious infotainment outlet can fool thousands or perhaps millions of real people as that fact gets repeated in different forms and amplified with nobody checking for a valid source.

Llms are no more robust.


Feel free to accuse the Germans. Russian bribes is basically why they have some of the most expensive energy in the world now. They're surprisingly corrupt for a "developed" "high tech" nation.

Search Gerhard Schroder for more info.


And Merkel, just as much as Schroeder.


Merkel was the worst european politician by a lightyear (or two). Maybe growing up in East Germany affected her negatively, don't know but these days she is a huge (and publicly outspoken) putin and russia apologist. Looking at history of her political moves, she was actually the same before, there just wasn't such an obvious war against whole Europe so it all could be labeled as 'low cost gas and oil is good', probably mixed with typical german 'we must atone for the sins of our grandparents' backwhipping.

Current russian war in Ukraine is also her doing. Making german military a joke, sending tens if not hundreds of billions euros to russia. She still admits no mistakes at all, despite being very actively hated across whole eastern part of EU. When asked directly about any of this she just goes into her fairy tale mental space not anchored in reality.

Overall she did a lot of long term harm. I don't believe she is evil at the core, just severely delusional, easy to manipulate and overall a bad, very bad leader. Wake me up when regular germans realize what rest of EU grokked a decade ago.


The fact that she gets a pass from lots of people is somewhat confusing to me. Clearly she is a major cause, whether through incompetence or malice isn't really all that important, though her most recent utterances make me now lean towards 'malice' more than 'incompetence' when before it was the latter (and a dose of hope that this time around it will be different).


Not if you consider that you need to either renew or add battery capacity (and panels and power electronics) after x years? Or did you take that into account?


That doesn't impact payback cost, if the batteries & panels last longer than 8-9 years (and they do).

It's just one metric.


x = ~25 years for the panels. They're paid off long before that.


The good news is: there are still off-site backups.

The bad news is: they're in North Korea.


"Your Holiness! I have terrible news! Jesus has returned!"

"But that's a blessed event? How could that be terrible?"

"He appeared in Salt Lake City."


Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: