Perl::Critic::Policy::Subroutines::RequireFinalReturn - End every path through a subroutine with an explicit C statement.


Perl-Critic documentation  | view source Contained in the Perl-Critic distribution.

Index


NAME

Top

Perl::Critic::Policy::Subroutines::RequireFinalReturn - End every path through a subroutine with an explicit return statement.

AFFILIATION

Top

This Policy is part of the core Perl::Critic distribution.

DESCRIPTION

Top

Require all subroutines to terminate explicitly with one of the following: return, carp, croak, die, exec, exit, goto, or throw.

Subroutines without explicit return statements at their ends can be confusing. It can be challenging to deduce what the return value will be.

Furthermore, if the programmer did not mean for there to be a significant return value, and omits a return statement, some of the subroutine's inner data can leak to the outside. Consider this case:

    package Password;
    # every time the user guesses the password wrong, its value
    # is rotated by one character
    my $password;
    sub set_password {
        $password = shift;
    }
    sub check_password {
        my $guess = shift;
        if ($guess eq $password) {
            unlock_secrets();
        } else {
            $password = (substr $password, 1).(substr $password, 0, 1);
        }
    }
    1;

In this case, the last statement in check_password() is the assignment. The result of that assignment is the implicit return value, so a wrong guess returns the right password! Adding a return; at the end of that subroutine solves the problem.

The only exception allowed is an empty subroutine.

Be careful when fixing problems identified by this Policy; don't blindly put a return; statement at the end of every subroutine.

CONFIGURATION

Top

If you've created your own terminal functions that behave like die or exit, then you can configure Perl::Critic to recognize those functions as well. Just put something like this in your .perlcriticrc:

    [Subroutines::RequireFinalReturn]
    terminal_funcs = quit abort bailout

BUGS

Top

We do not look for returns inside ternary operators. That construction is too complicated to analyze right now. Besides, a better form is the return outside of the ternary like this: return foo ? 1 : bar ? 2 : 3

AUTHOR

Top

Chris Dolan <cdolan@cpan.org>

COPYRIGHT

Top


Perl-Critic documentation  | view source Contained in the Perl-Critic distribution.