in reply to An example of programming by contract
Stylistically, I'd probably use sub refs instead of the string eval, too. If your pre- and post- conditions are in a package, UNIVERSAL::can comes to the rescue. Otherwise, this is an opportunity for a little symbol table muckery:
Or you could build a hashref of validators, or cache them instead of explicitly going to the symbol table, or use the Listener pattern, or do all sorts of things.sub validate { my $input = shift; my %arg = @_; for (@{$arg{as}}) { my $func = "validate_$_"; my $package = __PACKAGE__ . '::'; no strict 'refs'; if (exists ${ $package }{$func}) { $func = *{ ${ $package }{$func} }{CODE}; return unless $func->($input); } else { # throw exception and/or return } } warn "validated $input"; return 1; }
|
---|