(This has been cross-posted to my use.perl journal.)
The following code has a bug:
sub _select_fields { my $self = shift; my @fields; if ($self->request->param('rev_type') eq 'both') { push @fields, ('rev', 'theater_avg'); } elsif ($self->request->param('rev_type') eq 'total') { push @fields, 'rev'; } else { push @fields, 'theater_avg'; } push @fields, 'num_theaters', 'day_multiple'; return @fields; }
It turns out that it's supposed to default to "both" instead of its current invisible "loc_avg" default. Further, a new feature has been requested: "day_multiple" should only show up if specifically requested. I certainly didn't want to add to this nasty if/else chain, so I made it a hash. Now it's nice and easy to read.
sub _select_fields { my $self = shift; my %rev_types = ( both => [ qw/rev theater_avg num_theaters/ ], total => [ qw/rev num_theaters/ ], loc_avg => [ qw/ theater_avg num_theaters/ ], all => [ qw/rev theater_avg num_theaters day_multip +le/ ], ); my $rev_type = $self->request->param('rev_type'); $rev_type = 'both' unless exists $rev_types{$rev_type}; return @{$rev_types{$rev_type}}; }
A boolean "if" isn't such a bad thing (that's the unless in the above code.) It's the nasty if/elsif/else chains that keep cropping up that are problematic. Also note that we've added functionality but the code is shorter and easier to read. This actually happens quite frequently if we look at our "if" statements and figure out how to excise them.
Remember kids: friends don't left friends use "if."
Cheers,
Ovid
New address of my CGI Course.
In reply to A short, "iffy" rant by Ovid
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |