Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

Re: Params::Validate - a powerful tool for robust subroutine design

by autarch (Hermit)
on Jan 24, 2006 at 07:16 UTC ( [id://525121] : note . print w/replies, xml ) Need Help??

in reply to Params::Validate - a powerful tool for robust subroutine design

One style note I'd like to make. At $DAYJOB other coders liked the concept of declaring an API and checking it, but they felt like having a big clock of param spec code in the subroutine body was distracting, especially for short subs.

I've started using this style whenever possible to work around that problem:

{ Readonly my $spec => { size => { type => SCALAR }, color => { type => SCALAR, regex => qr/^(?:red|green|blue)$/i }, }; sub item_by_size_and_color { my %p = validate( @_, $spec ); ... } }

This pulls the parameter declaration out of the sub body but puts it right next to the sub. The use of Reaodnly is entirely optional, and I should point out that it only works with the XS version of Readonly, the pure Perl version will cause segfaults if you use the XS version of Params::Validate (perl magic in the internals is a huge PITA for XS code).

Generally speaking, I'm really liking the above style, though if you need to calculate some part of the spec dynamically per request, it won't work.

We also created a library to simplify "type declaration", so we have code like this:

{ size => SCALAR_TYPE, color => RGB_COLOR_TYPE( default => 'blue' ), ... }

I'd like to turn this into a CPAN module eventually, maybe something like Params::Validate::Types.

And finally, it's worth noting that Params::Validate is fairly flexible in its inputs. The parameters can be given as a hash (in @_) or a hashref (in $_[0]).