I have had a difference of opinion with a colleague regarding the use of multiple return statements in a sub routine, as opposed to using nested conditionals. I'd like to hear thoughts from the rest of the community on this topic. Please consider the following subroutines: (all method and variables are fake just to illustrate the example)
sub foo
{
my($self) = @_;
my $authentication = $self->authenticate_user();
if(! defined($authentication)){
return {status=>0, error=>"Authentication Failed", external_id=>
+undef};
}
my $profile = $self->get_user_profile();
if(! $profile->is_active()){
return {status=>0, error=>"User is not active", external_id=>und
+ef};
}
my($external_id) = $self->find_external_id($profile);
if(! defined($external_id)){
$external_id = $self->send_profile_to_partner($profile);
}
return {status=>1, error=>undef, external_id=>$external_id};
}
### As Opposed to
sub bar
{
my($self) = @_;
my $status = 0;
my $error = undef;
my $external_id = undef;
my $authentication = $self->authenticate_user();
if(! defined($authentication)){
$error="Authentication Failed";
}else{
my $profile = $self->get_user_profile();
if(! $profile->is_active()){
$error="User is not active";
}else{
my($external_id) = $self->find_external_id($profile);
if(! defined($external_id)){
$external_id = $self->send_profile_to_partner($profile);
}
}
}
return {status=>$status, external_id=>$external_id, error=>$error};
}
Corrected a typo causeing bar to always return 0 for status.
The hash reference being returned could be defined at the beginning for either implementation, to make adding or removing values from it easier, my real question is simply regarding the style of using a return to short circuit the sub routine, and opposed to the nested if/else structures.
Which of these implementations would you prefer and why?
Thank you all in advance for sharing your input. I'm interested to hear what people think
They say that time changes things, but you actually have to change them yourself.
Andy Warhol
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.