Perl: Named parameters validation best practice

人盡茶涼 提交于 2019-12-22 10:29:15

问题


I am using named parameters in class method calls and was wondering if there is a best practice to make sure no unknown parameters are passed. Here's what I am doing

sub classmethod {
    my $self = shift;
    my %args = (
        "param1" => "default1",
        "param2" => "default2",
        @_
    )

    if (my @invalid = grep { !/^(param1|param2)$/ } keys %args) {
        croak "received unknown arg(s) ".join(",", @invalid)." from ".caller();
    }
}

Is that a proper way to go forward, or could this cause a performance problem?

Best, Marcus


回答1:


You could use Params::Validate. Another option is Params::Check

If params are fixed, then its best to validate them during development, with the option to turn off validation when live.




回答2:


There are a lot of ways to pass parameters in Perl, and a lot of ways to validate them (or not).

If you are using the explicit default idiom anyway and want a light touch, then you can check that the number of keys in the hash are equal to the number of keys in the defaults. Getting the number of keys is a fast operation that doesn't depend on the size or contents of the hash table. If there is a key "in" @_ that isn't in %default, then %args will have more keys.

The disadvantage that this has over your current solution is that it doesn't tell you which key is unexpected.

sub classmethod {
    my $self = shift;
    my %args = (
        param1 => "default1",
        param2 => "default2",
        @_
    );
    keys %args == 2 or croak "received unknown arg. args: " . join(", ", keys %args);
}

Or do something like this to avoid having to change the number when you change the number of parameters.

sub classmethod {
    my $self = shift;
    my %default = (
        param1 => "default1",
        param2 => "default2",
    );
    my %args = (%default, @_);

    keys %args == keys %default or croak 'unknown arg' . join(", ", keys %args);
}


来源:https://stackoverflow.com/questions/19514694/perl-named-parameters-validation-best-practice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!