(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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.