Another way is to refactor them into four separate classes, based on your $dcr_type variable. A fifth class, would be used as a sort of factory and would decide which subclass to return based on the value of the $dcr_type. You would still have the if...then logic, but it is hidden by a separate layer of abstraction. It would go something like this (this is just an example, so the code below is very skimpy)
package factory; #We don't need any logic in this constructor, so... sub new { my $class = shift; bless {}, $class; } sub getInstance { my ($class, $dcr_type, @row) = ( $_[0], uc $_[1], @{$_[2]} ); if ($dcr_type eq "CONTACT"){ return contact->new(@row); } elsif($dcr_type eq "LITERATURE"){ return literature->new(@row); } elsif($dcr_type eq "FAQ"){ return faq->new(@row); } elsif($dcr_type eq "ORGANIZATION"){ return organization->new(@row); } } package contact; sub new {...} sub doTheDeed{ return ('HQ' , undef); } package literature; sub new {...} # @_row is this classes local version of the @row parameter sub doTheDeed{ return (undef, $_row[4]) } package faq; sub new {...} # @_row is this classes local version of the @row parameter sub doTheDeed{ return (undef, $_row[2] eq 'Service' ? $_row[3] : $_row[4]); } package organization; sub new {...} # @_row is this classes local version of the @row parameter sub doTheDeed{ my @ret = ($_row[2], undef); $ret[0] = 'HQ' if ($_row[0] eq 'Headquarters'); return @ret; }
Now your main body code will look like:
my $fact = factory->new(); my $instance = $fact->getInstance($dcr_type, @row); return $instance->doTheDeed();
In reply to Re: Rethinking Your Program's If-Thens
by Steve_p
in thread Rethinking Your Program's If-Thens
by princepawn
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |