Steve Bertrand wrote:
> I've been reading both the Cookbook and HOP
HOP?
> My question is, is if it is common practise to use named parameters
> for incoming arguments to functions/methods.
I tend to code for personal, private use, so I have the luxury of
changing my mind as the mood suits me. I once saw a book with an apt
title -- "Enough Rope to Shoot Yourself in the Foot: Rules for C and C++
Programming". That said, finding, learning, and practicing conventions
is a never-ending, but beneficial, journey. There are way-points, but
there is no "ultimate" destination.
I tend to use positional parameters if there is only one argument, or if
there are a few arguments and their order is fixed:
my $y = func($x);
my $n = array_func(@a);
my $m = point_func($x, $y);
Otherwise, I use hash parameters (with CGI.pm style keys):
my $e = func2(
-foo => 1.23,
-bar => ['a', 'b'],
-baz => {-bozo => $x},
);
> is it recommended that a project should keep consistent with ALL
> methods/functions in this regard whichever way one decides?
Consistency is important, but you have to set boundaries and use your
judgment. "One size fits all" hasn't worked for me.
> I'm tired of trying to pop/shift error check the way I have been.
> It's a nightmare when I want to add a new argument to an API, as it
> immediately causes great (oftentimes subtle) havoc until I fix all of
> the callers.
The C library approach of putting error codes into function return
values can work if the error code cannot be mistaken for a valid return
value:
system "$line"
and die "$0 ERROR system '$line' failed: $!"
I've thought about returning arrays and/or hashes with encoded errors,
but haven't gone down that path.
In general, I now use die() or some variant:
use Carp;
sub func3
{
...
confess "arguments must be hash"
if (scalar @_) % 2;
die() generates an exception outside of the normal flow of code, and
eliminates the return value/ error code conflict. You can trap die()
with eval():
### in a test script:
$e = eval {
func3("foo");
};
ok(!defined $e # 1
&& $@ =~ /arguments must be hash/,
"call with single argument should fail",
) or warn Data::Dumper->Dump([$e, $...@], [qw(e @)]);
It is possible to nest eval/ die, and "re-throw exceptions".
There is also an OO exception handling module you may want to look at --
Error.pm.
Learning and following conventions helps me when I use other people's
code and vice versa. As the code becomes more complex, a simple and
consistent coding style can mean the difference between success and
failure. But, all this requires planning and effort. Whether or not I
put out the effort depends upon who will be using the code and for how
long. Short-but-sweet scripts and cryptic one-liners have styles unto
themselves. And, there is a place for quick-and-dirty hacks. YMMV.
TIMTOWTDI.
HTH,
David
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/