If you're really feeling "paraniod", you have to be very
careful not to fall in the "defensive programming" mode
which can be very damaging. With defensive programming,
your function which should do something, but receives bad
input, does nothing. You just created a ticking time-bomb,
because sooner or later some other function is going to
set it off, and you'll have no idea where the problem
came from.
Consider:
sub OpenSomething
{
my ($param) = @_;
# What kind of an idiot would forget the foo parameter!
return unless (defined $param->{foo});
my $thing = new Object ($param->{foo}, $param->{zoo});
$thing->open($param->{foozoo});
return $thing;
}
sub CloseSomething
{
my ($thing) = @_;
$thing->close();
}
Now, in your program you will call OpenSomething(), which
might actually return nothing. You forget to check if
you got anything back, so later on when you call
CloseSomething() you get an error. The error, it would seem,
originates in CloseSomething().
Of course, you could just get more defensive:
sub CloseSomething
{
my ($thing) = @_;
# Maybe they forgot to pass the parameter?
return unless (defined $thing);
$thing->close();
}
Now what you have done, effectively, is swept all these
errors under the carpet. They don't manifest, and they
don't cause "errors" in the visible sense, but there
may be problems with the way your program runs that doesn't
make any sense.
It is probably better to die and get it over with:
sub OpenSomething
{
my ($param) = @_;
# What kind of an idiot would forget the foo parameter!
die "No 'foo' param passed to OpenSomething()" unless (defined $
+param->{foo});
my $thing = new Object ($param->{foo}, $param->{zoo});
$thing->open($param->{foozoo});
return $thing;
}
sub CloseSomething
{
my ($thing) = @_;
die "Cannot CloseSomething() with undefined parameter" unless (d
+efined $thing);
$thing->close();
}
Using die in this capacity is similar to the ASSERT()
macro used in C programming which will completely halt the
program if something is seriously out of line.
If the train comes off the tracks, you'd best stop it. | [reply] [d/l] [select] |
I can see your point.
I've always tried to throw something kind of error in my functions if things don't go right. I think a die or an error code is good.
I probably forget often enough, I haven't really used subs/functions since I started in Perl. I need to get it down. I guess the funny way of passing variables into them kind of turned me off. And since I don't do anything too complex (most of what I do is fairly procedural) I haven't had a real need for it.
In the future, maybe :)
| [reply] |
OOps
Forgot to login
:)
Otijim | [reply] |