Should a subroutine croak when called with more arguments than expected or should the extra arguments simply be ignored?
#!/usr/bin/env perl
use warnings;
use strict;
sub routine {
my ( $a, $b ) = @_;
return $a * $b;
}
my $reslult = routine( 4, 5, 6 );
Generally I don't bother writing argument checks by hand, but I think the correct response is to croak. That way you can extend the function to take optional arguments later without breaking existing callers.
If your Perl is new enough, you can install and use Function::Parameters
like this:
use warnings;
use strict;
use Function::Parameters qw(:strict);
fun routine($x, y) {
return $x * $y;
}
my $result = routine(4, 5, 6); # croaks automatically
(Btw, don't call your variables $a
or $b
: those names are used by sort
and exempt from strict 'vars'
checks.)
That's somewhat subjective, even within a project. In some cases excess arguments might suggest a real problem on the part of the caller and worth checking, especially if the subroutine is part of a published library. On the other hand, if the subroutine is for internal consumption, ignoring extra arguments may make it more convenient. (For example, you want it to operate on the first element in an array but don't bother isolating that value and just give it the whole array.)
Thinking about the use cases, and whether those extra arguments are just junk or might suggest a real problem, and also what the performance issues are should help you decide if it is worth it. Another consideration: will code in the subroutine naturally catch mistakes that might cause extra arguments to appear. If so, testing the argument count may be redundant and probably less useful than the specific error caught later.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With