Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Re: Control Flow - Multiple returns or nested conditionals (we're done here)

by tye (Sage)
on Oct 07, 2010 at 23:03 UTC ( #864107=note: print w/replies, xml ) Need Help??

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.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://864107]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (6)
As of 2021-07-29 10:20 GMT
Find Nodes?
    Voting Booth?

    No recent polls found