perl 防御性编程 (die, assert, croak)

标签 perl assert die defensive-programming

在 perl 中进行防御性编程的最佳(或推荐)方法是什么? 例如,如果我有一个必须使用(定义的)SCALAR、ARRAYREF 和可选的 HASHREF 调用的 sub。

我见过的三种方法:

sub test1 {
    die if !(@_ == 2 || @_ == 3);
    my ($scalar, $arrayref, $hashref) = @_;
    die if !defined($scalar) || ref($scalar);
    die if ref($arrayref) ne 'ARRAY';
    die if defined($hashref) && ref($hashref) ne 'HASH';
    #do s.th with scalar, arrayref and hashref
}

sub test2 {
    Carp::assert(@_ == 2 || @_ == 3) if DEBUG;
    my ($scalar, $arrayref, $hashref) = @_;
    if(DEBUG) {
        Carp::assert defined($scalar) && !ref($scalar);
        Carp::assert ref($arrayref) eq 'ARRAY';
        Carp::assert !defined($hashref) || ref($hashref) eq 'HASH';
    }
    #do s.th with scalar, arrayref and hashref
}

sub test3 {
    my ($scalar, $arrayref, $hashref) = @_;
    (@_ == 2 || @_ == 3 && defined($scalar) && !ref($scalar) && ref($arrayref) eq 'ARRAY' && (!defined($hashref) || ref($hashref) eq 'HASH'))
        or Carp::croak 'usage: test3(SCALAR, ARRAYREF, [HASHREF])';
    #do s.th with scalar, arrayref and hashref
}

最佳答案

use Params::Validate qw(:all);

sub Yada {
   my (...)=validate_pos(@_,{ type=>SCALAR },{ type=>ARRAYREF },{ type=>HASHREF,optional=>1 });
   ...
}

关于perl 防御性编程 (die, assert, croak),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21970799/

相关文章:

xml - 我如何在 Perl 中解析 JSON?

java - JUnit assertTrue 异常

php $fopen 错误

perl - SOAP::Lite 连接到 SSL 服务器

perl - 如何将 YAML 映射表示为流映射 {},而不是多行 block 映射?

junit - 在 JUnit 中对 float 和 double 值使用assertTrue 可以吗?

c++ - 类似的断言语句给出不同的结果

java - 如何让我的百分比在我的 Dice 计划中发挥作用?

Php:何时使用 pthread

file - 将 `close` 替换为 `open` `/dev/null` ?