Re: single return from function
Alfredo Chavez <[email protected]> Tue, 11 Dec 2012 10:10:33 -0600
| Newsgroups | gmane.comp.programming.refactoring |
|---|---|
| Message-ID | <[email protected]> |
From chapter 9 "Simplifying conditional expressions":
"I often find I use Replace Nested Conditional with Guard Clauses
when I'm working with a programmer who has been taught to have only
one entry point and one exit point from a method. One entry point is
enforced by modern languages, and one exit point is really not a
useful rule. Clarity is the key principle: if the method is clearer
with one exit point, use one exit point; otherwise don't."
Does that clarify the issue?
El 11/12/2012 03:14 a.m., Willem Bogaerts escribi=F3:
>
> > 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.
>
>=20
[Non-text portions of this message have been removed]
------------------------------------
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]=20
[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/