This post originated from an RSS feed registered with Agile Buzz
by Mark Levison.
Original Post: Multiple Returns from a Single Method
Feed Title: Notes from a Tool User
Feed URL: http://feeds.feedburner.com/NotesFromAToolUser
Feed Description: Thoughts about photography, software development, reading, food, wine and the world around us.
It’s funny just about the only thing anyone really objected to from my recent post on Minimal Coding Style was multiple return statements.
Lets start by looking back to where this idea stems from. As best I can tell objections to multiple returns stem from Dijkstra's 1968 paper “Go To Statement Considered Harmful”. From David Tribble who has written a Retrospective on the letter, from the introduction:
This paper was written at a time when the accepted way of programming was to code iterative loops, if-thens, and other control structures by hand using goto statements. Most programming languages of the time did not support the basic control flow statements that we take for granted today, or only provided very limited forms of them. Dijkstra did not mean that all uses of goto were bad, but rather that superior control structures should exist that, when used properly, would eliminate most of the uses of goto popular at the time. Dijkstra still allowed for the use of goto for more complicated programming control structures.
Here is what I believe about methods:
Short, Short, Short – at most one screen long – anything more requires the reader to scroll up and down to understand the code.
Do only one thing – for the ultimate anti example of this: Munger (MacOS 7/8/9) the swiss army knife of memory allocation that did different things depending on the combination of parameters. Note the linked article doesn’t describe a fraction of what Munger did. Be afraid.
Have descriptive (but not verbose) name.
Be simple and easy for the maintainer to read – this implies reducing the complexity of the control structures.
Some reasons I dislike the single exit argument:
If there are cases that aren’t applicable (invalid method arguments, …) I like to exit the method early to avoid additional indentation.
Without early exits we have to keep track of whether each additional branch was intended to execute.
Without early exits the ‘result’ might accidentally get changed, meaning the wrong value is returned.
If more code is added later it might accidentally get run even though its author intended the method to be finished.
If you need to clean up use a try/finally block since even early returns pass through finally blocks.
If multiple return statements make a method hard to read then the method is probably too large. In addition most IDE’s will allow you to highlight the control statements in any colour you need to make them visible.