Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: Parameter Asserts - How do you use them?

by adrianh (Chancellor)
on Apr 16, 2003 at 21:16 UTC ( [id://251054]=note: print w/replies, xml ) Need Help??


in reply to Parameter Asserts - How do you use them?

How would I code "parameter asserts"? I checked the camel book, but there doesn't seem to be an "assert" keyword.

Depending on mood I may do something like this:

sub new { my ($self, %param) = @_; my ($dbh, $foo) = map { $param($_) || croak "need $_" } qw(dbh foo +); # ... stuff that uses $dbh and $foo ... }

or use a module like Params::Validate or Carp::Assert.

Do you personally use them in your code? Why or why not?

Yes, I tend to use them. For two reasons:

  1. They make design decisions explicit in the code. Saying:

    croak "need a foo" unless UNIVERSAL::isa($foo, 'Foo');

    says a lot about your code's contracts and, unlike paper documents or UML diagrams, won't get out of sync with the code.

  2. It makes debugging easier. You get a specific error message near the place where the "bad" data went in (as opposed to a possibly less specific error message where the "bad" data gets used).

Reasons not to use them:

Efficiency. Assertions take time and in a tight loop or in a method that is called many times this can add up. You can use constants to allow you to switch your assertions on/off at compile time (the documentation for Carp::Assert has some examples of this.) There are some indications that there will be "real" assertions in the next perl5 that can be switched on/off without a compile time penalty.

When it's obvious that they're not needed (for some definition of "obvious" :-). For example, in:

package Foo; use Carp; use Regexp::Common; # ... rest of class ... sub add { my ($self, $n) = @_; croak "need Foo object" unless UNIVERSAL::isa($self, 'Foo'); croak "need number" unless $n =~ $RE{num}{real} $self->{total} += $n; };

the two assertions are redundant (IMHO). If $self isn't a Foo object then somebody is calling my method as a subroutine and deserves all that they get. If $n isn't a number then the addition is going to throw a warning anyway.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (4)
As of 2024-04-20 04:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found