Re: single return from function

Willem Bogaerts <[email protected]> Tue, 11 Dec 2012 10:14:04 +0100
Newsgroups gmane.comp.programming.refactoring
Message-ID <[email protected]>
> On the internet, I found somewhere* that the Refactoring book
> advocates for a single return from a function (thus, promoting
> assigning values to a variable, such as result, and then say return
> result; at the end).
> 
> Is that true?
> 
> I couldn't find it anywhere in the online catalog.

I don't know the book by heart, but it makes a lot of sense. A return
statement is effectively a "goto end" statement. And I hope we all know
why gotos are bad.

That said, it is a pain to extract code with more than one return
statement into its own method, as it still means "goto end", but the
endpoint has changed.

But...

Off course there are some things that may be bad, but only
theoretically. As others have already remarked, a guard clause as a
first statement is OK. Why? Simple: you can only extract the code with
or without that first statement, and in both cases the behaviour is
preserved. The other case is putting the return statement as the last
statement in the function, as it makes the "goto" part of the meaning
irrelevant. And that is where the single point of exit comes from.

Best regards,

Willem Bogaerts.


------------------------------------

Yahoo! Groups Links

<*> To visit your group on the web, go to:
    http://groups.yahoo.com/group/refactoring/

<*> Your email settings:
    Individual Email | Traditional

<*> To change settings online go to:
    http://groups.yahoo.com/group/refactoring/join
    (Yahoo! ID required)

<*> To change settings via email:
    [email protected] 
    [email protected]

<*> To unsubscribe from this group, send an email to:
    [email protected]

<*> Your use of Yahoo! Groups is subject to:
    http://docs.yahoo.com/info/terms/