4

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 );
sid_com
  • 24,137
  • 26
  • 96
  • 187
  • 5
    This is really just my opinion: A subroutine is written by a programmer, and used by a programmer. If it is documented to handle a variable number of arguments: Handle them. If it is documented, and meant to handle just N of them, then croak when you don't see exactly N. e.g. If you claim that a subroutine multiplies two numbers, and see it being called with three, this means the programmer who wrote the call doesn't know what he/she is doing. Croak. – ArjunShankar Feb 12 '13 at 16:10

2 Answers2

7

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.)

melpomene
  • 84,125
  • 8
  • 85
  • 148
7

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.

William
  • 4,787
  • 2
  • 15
  • 14