|Just another Perl shrine|
Params::Validateby rinceWind (Monsignor)
|on May 16, 2004 at 22:08 UTC ( #353826=modulereview: print w/replies, xml )||Need Help??|
Item Description: Validation of parameters passed to a subroutine
Whereas C++ and Java go to great lengths to ensure that the data types of any arguments passed to a function, match what is expected, perl is often criticised for not enforcing anything.
Perl 6 will address this issue, but in the mean time, any subroutines you write are passed an array @_ containing a potential hotch-potch of scalars and references, blessed or otherwise.
Although it's nice to write code that can DWIM given a parameter of varying data types, this is always an extra effort to implement. Also, what will your sub do when passed a SCALAR when it's expecting an ARRAYREF? At best, it will die with a run-time error, and a message which likely as not, would not be immediately obvious.
Enter Params::ValidateBy default, this module exports the functions validate and validate_pos. Params::Validate caters for two calling conventions: named parameters and positional parameters, which are validated by validate and validate_pos respectively. Unfortunately you can't mix them; any positional parameters before your list of key/value pairs need to be removed first. In fact, this is the way to use Params::Validate to handle method calls. Examples:
As is apparent, the call to validate or validate_pos is quite straightforward and edifying to someone else looking at the code.
It's also quite easy to add such validation to existing code, for an immediate gain in robustness without too much cognitive effort. The module provides a whole host of tools for validating your argument list - I have just scratched the surface.
Error handlingWhen the parameter validation fails, the default action it to croak, with quite a helpful message about which parameter is invalid and why. You can elect to use a callback to catch validation errors instead.
ConclusionI am a convert to using this module. I recommend it for CPAN modules and for corporate coding standards.
UpdateI have had some interesting dependency issues with modules of mine that are using Params::Validate. I have seen CPAN pull in Ponie via Attribute::Handlers. Why would I want the Parrot/Ponie stuff coming into my production environment ?! I asked Arthur Bergman about this, and apparently it is a spurious dependency picked up by CPAN.pm, apparently sorted in a later release of Attribute::Handlers.
I did notice also that ActiveState's module status page was showing any of my modules that use Params::Validate, as having a dependency on Ponie.