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:
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.
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.
|
|---|