Early return is probably the single most effective refactoring tool I've found. It is the single technique that has offered the greatest improvements in code clarity and simplicity for me over the last decade.

I almost always find several cases of "if" + "return" to be much better code than having "elsif"s.

The second-most-useful tool is throwing exceptions, which is another type of early departure. "next if ..." at the top of a loop is also extremely handy.

It is very useful to get the small exceptions out of the way up front without having to complicate the lion's share of the code by burying it in nested flow control.

Compare the simplicity of:

return ...; vs. my $return; ... $return= ...; # Put some flow control structure here # to prevent any code between here and # the 'return' from running ... return( $return );

Requiring a single use of the return keyword does no good. It doesn't lead to knowing exactly what the function can return. It just leads to return @computed_above; and then having to go find all of the ways in which @computed_above might be manipulated. So it usually makes the code less clear (and more complicated).

Multiple exits from a subroutine is not something to avoid. Quite the opposite.

- tye        


In reply to Re: Control Flow - Multiple returns or nested conditionals (we're done here) by tye
in thread Control Flow - Multiple returns or nested conditionals by JediWizard

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.