http://www.perlmonks.org?node_id=864107


in reply to Control Flow - Multiple returns or nested conditionals

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        

Replies are listed 'Best First'.
Re^2: Control Flow - Multiple returns or nested conditionals (we're done here)
by Your Mother (Archbishop) on Oct 08, 2010 at 02:58 UTC

    Well that's exactly what I said… except, you know, better, and with illustrative examples, and a firm conclusion, and stuff.