Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I didn't realize I instinctively picked up the early return habit until I started doing iOS development, where it seems the convention encouraged by apple is nesting rather than early returning.

I prefer the early return style. I generally try to put all error handling / sanity checking code up top with early returns (ie, the preconditions of the function), so that the "meat" of the code at the bottom of the function can be more concise and easier to grok. However, this requires a reading style of "first read the bottom of the function to get the gist of it, and then read all of the pre conditions above it". Unfortunately I have to explain that to my coworkers, bu when I do, they seem to understand wha I'm going for.



Good old guard clauses. I use them for this exact purpose.

The admonition to use single returns from a function arose from the days when a) GOTO was the major flow-control primitive and b) Dijkstra and others were starting to build up a head of steam on the we-should-treat-programs-as-mathematical-proofs thing.

If you have a single return point out of a function, it's easier to prove various things about it.

But like a lot of findings, it broke loose of its moorings in the problems of that time and floated away to lead an exciting care-free life of its own.

Analysis has improved since then, but more to the point, single-return code often leads to carrying around a bunch of book-keeping variables whose only purpose it is to artificially prop up that nostrum. They do not relate to the problem domain: they add to the difficulty of understanding the code.

That's why I feel single-return is a principle that is well past its glory days. Return from a function where it makes sense.


I prefer early returns for precondition checking too. i.e. before anything interesting has occurred. Thinking about it though, I've just realized that the early-return problem is sort of a by-product of side effects. If your function simply takes input and produces an output, and you control where side effects are applied, then early returns are far less of an issue.




Consider applying for YC's Fall 2026 batch! Applications are open till July 27.

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

Search: