http://qs321.pair.com?node_id=864019

JediWizard has asked for the wisdom of the Perl Monks concerning the following question:

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