Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

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

by autarch (Hermit)
on Jan 24, 2006 at 07:16 UTC ( #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]).


Comment on Re: Params::Validate - a powerful tool for robust subroutine design
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://525121]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (7)
As of 2014-12-21 23:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (109 votes), past polls