Geeks With Blogs
Remi Sabourin's Blog Architecture, Management and everything else

Apparently there was a little stir among the senior developers today whether multiple returns in a function/method's implementation is an absolute evil - some taking both absolutely agree or absolutely disagree.  My comment:

If it's a long function, I try to avoid multiple returns and have a single exit point. If a short function (15 lines or less), it's not really that important, as long as the code is readable. Usually the discussion of exit points hides a bigger issue that the functions haven't been decomposed enough and you have a long function that needs help in understanding - solution: break up/out the function.

With a long function, I have already added a return statement right at the start that executes based off a simple short circuit condition, and this was more readable/intuitive compared to exit points being nested deep in a function or nesting the entire implementation in an IF statement.

In general, in implementing I try to write so someone else has a quick understanding of my code and it's self documenting. If someone has to trace through my code to figure out where/when it's returning and so forth, going back and forth with different parameters that potentially could be passed in, they might as well have implemented it since they spent way too much time understanding my code.  There's more that I could say regarding functional decomposition, case statements, else clauses, error handling, etc. Ideal path of execution is a broad topic that goes beyond single point of exit. 

I will add that multiple exit points is bad if you 'forget' to do something common to any execution path due to leaving the function too early - ie. things like cleanup or logging.  But did you know that you can wrap your entire implementation later with a Try... Finally and the Finally will execute regardless of how you exit the function (ie. via a return OR an exception thrown)? Kindof kewl...

Posted on Monday, June 9, 2008 8:10 PM Best Practices | Back to top


Comments on this post: Multiple Function Exit Points - Bad?

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Remi Sabourin | Powered by: GeeksWithBlogs.net