NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.
All the Perl that's Practical to Extract and Report
Stories, comments, journals, and other submissions on use Perl; are Copyright 1998-2006, their respective owners.
Aack! That's ugly (Score:2)
No, I wouldn't use a switch-like construct there. What's the point of a label when there's a much cleaner solution? I would probably use a dispatch table like the following:
my %dispatch = (
foo => \&foo,
bar => \&bar,
baz => \&baz
);
#later
if ( exists $dispatch{$function} ) {
$dispatch{function}->(@args);
}
else {
die "No such function ($function)";
}
I don't know, maybe it's just me, but that seems much cleaner and
Re:Aack! That's ugly (Score:2)
Re:Aack! That's ugly (Score:2)
I humbly submit an example of when SWITCH can go horribly wrong. The temptation to use labels for control flow when they are not required makes bugs like this more likely.
while ( my $data = $t_sth->fetchrow_arrayref ) { /= PRECISION;
my ( $amt, $id ) = @$data;
$amt
SWITCH: {
$id == $CASH && ($tcash += $amt) && last SWITCH;
$id == $ACCOUNT && ($taccount += $amt) && last SWITCH;
$id == $CHECK && ($tcheck += $amt) && last SWITCH;
$id == $GIFT && ($tgift += $amt) && last SWITCH;
$id == $VOUCHER && ($tvoucher += $amt) && last SWITCH;
$id == $CC_MAN_AUTH && ($tcc_man_auth += $amt) && last SWITCH;
($tcredit += $amt);
}
}
Many people (including me) will miss the bug. The problem here is the short circuit behavior when the increment results in a false value. Most of the time, this code worked. I asked chromatic [perl.org] for help and he wrote the following:
my %totals;
/= PRECISION;
@totals{$CASH, $ACCOUNT, $CHECK, $GIFT, $VOUCHER, $CC_MAN_AUTH} =
\($tcash, $taccount, $tcheck, $tgift, $tvoucher, $tcc_man_auth);
while ( my $data = $t_sth->fetchrow_arrayref ) {
my ( $amt, $id ) = @$data;
$amt
if (my $totalvar = $totals{ $id }) {
$$totalvar += $amt;
}
else {
$tcredit += $amt;
}
}
His code worked, mine didn't. Now some people would argue that my code's failure is a result of my not paying attention to the short-circuiting behavior of &&, but that's not the real issue. The underlying problem here stems from my having duplicated the same code over and over. chromatic didn't make that mistake. He applied the logic exactly once, I applied it multiple times. Essentially, I cut-n-pasted the code. This leaves less room for thought and more room for error. For every one of your programmers who wants to use that SWITCH construct, point out the duplicate code. That is where a large part of the problem lies.
Reply to This
Parent
Re:Aack! That's ugly (Score:2)
Maybe I can turn this into a "THAT IS FIRE, DO NOT TOUCH THE FIRE" ;-)
Re:Aack! That's ugly (Score:2)
I saw the "bug" when I saw the code, but then I thought "the programmer wouldn't have used that construct if ($tcash += $amt) could ever yield zero!".
I like pie.