Hacker News new | past | comments | ask | show | jobs | submit login

Returning early is, in my experience, a recipe for disaster.

Even in trivial 4 line functions I assign my return values to a variable and then return that at the end of the function.

This may just be my pedantry left over from when I first studied C at university, but more than once I've spent a while trying to figure out why a return value wasn't what I was returning (from some code that had been previously written by someone else) only to find that there was a return statement on the 3rd or 4th line of the function.

One could certainly argue that if a function were concise and readable and commented and all that stuff then this wouldn't be a problem, but that's not always the case and a little return statement sitting someone in the middle of the function can really throw you sometimes




I've noticed most coding style tips only make sense in concert. I'm assuming the reason you got bitten was that you were looking at a function which was several pages long (ie, you didn't have time to read the entire function before makin an edit). The early return thing is a strategy I definitely subscribe to, but I works best when you favor lots of small functions rather than few long unctions


returning early is a good practice for all the guards and sanity checks you have to perform before the main logic of the function kicks in. if you use it this way, your function will visually consist of a bunch of small blocks each with a return, followed by one larger chunk of code that is the "actual" function, and where you can enforce a single return at the end.


I concur. This is how I have been structuring function bodies for a while now, and coworkers tend to easily follow the logic of both the whole function body and the "actual" work.




Join us for AI Startup School this June 16-17 in San Francisco!

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

Search: