-
Notifications
You must be signed in to change notification settings - Fork 262
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
discourage multiple exit points in a method (multiple return) #15
Comments
@daodennis This is a great suggestion -- thanks for participating here! I would be glad to look over an example. I sometimes struggle myself with whether multiple if some_condition:
return special_calculation()
return default and it's hard to argue with the readability of that. But I tend to agree that several exit points to a function (especially a deeply nested function) can be quite confusing. |
I would argue that this is like the short variable naming advice - if the exit points are easy to see and close together, it is still easy to parse and to understand what is going on. It certainly helps keep indentation down, where in more complicated cases this could lead to multiple nested if statements. |
Thanks @blagh I will add that sentiment. |
I would argue that there is nothing wrong with multiple returns per se but rather that if your function or method has become so huge that you can't look from one return to the next you have way bigger problems in your code base. |
It occurs to me I would also encourage having the "happy path" be the final But that could just be personal preference.
|
Someone recently shared "The Hitchiker's Guide to Python" with me, and it includes a section on this topic in its style guide: http://docs.python-guide.org/en/latest/writing/style/#returning-values |
It makes sense to have only one return statement in functions that have to do clean-up before returning in case of an error. Examples of such clean-up would be e.g. closing files and sockets or (in C) So in general, I don't think it is necessary to restrict yourself to one return. |
It can be confusing to have multiple exit points in a method.
With blessings of the powers that be I would like to submit an example (asking for guidance on where) to recommend using only one exit point in a method instead of multiple so it is easier to follow, i.e. only one return statement. Thoughts?
The text was updated successfully, but these errors were encountered: