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

I really tend to like early returns and use them often.

I usually try to make them use the form:

return x if y

To me, this makes it easier to follow a particular flow when reading code.

As soon as I encounter a return that matches it's conditional, I don't have to care about the rest of the method anymore.

During debugging, this also quickly lets me test assumptions by putting some log statements right after the return that should be occuring.

The only time early returns irk me is when they're deeply nested, but as mentioned by TFA and others in this thread, having deeply nested code is a bit of a code smell in its own right.



Those are typically considered to be guard clauses, and I agree that they're one of the more acceptable forms of early returns, but only if they're in the first few lines of the function. Returns in the middle of a 20-line function usually give me the twitches.




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

Search: