I use two general solutions, depending on how complex the problem is.
The first option is to use a table of function pointers:
%FLUT = (
'condition_1' => \&func_1,
'condition_2' => \&func_2,
'condition_3' => \&func_3,
);
$condition = ## reduce the input to a known condition
$FLUT{$condition}->(@args);
and since I happen to like object syntax, I have a simple little class that wraps function pointers up as objects:
package Command;
sub new {
my $type = shift;
my $O = shift;
bless $O, $type;
return ($O);
}
sub execute {
my $O = shift;
return ($O->( @_ ));
}
Naturally, it helps to make sure all the functions/objects in a table take the same list of arguments. That restriction appeals to me, because it helps me write code that ends in a known state no matter what. Nested if-else statements make it a little too easy to set one set of globals in one branch, and another set of globals in another, IMO. That makes it really difficult to decide what state the program is in when it leaves the outermost statement.
If a project involves serious branching, I'll occasionally roll my own linear state machine:
package Machine;
## new (nil) : Machine_ref
#
# trivial constructor
#
sub new {
my $self = bless {}, shift;
return ($self);
}
## execute
#
# run through the list of commands, halting when one of them fails
#
sub execute {
my $self = shift;
my $model = shift;
for $cmd (@{ $self->_get_commands() }) { # [1]
last if ( 0 == $cmd->execute ($model) ); # [2]
}
return();
}
###
# [1] iterate over the list of Command objects that belongs to the
# specific Machine, executing each one in turn.
# [2] drop out of the loop if any Command in the sequence returns
# a zero.
#
# in practice, this is equivalent to executing a set of
# short-circuit conditionals:
#
# if (<condition 1>) { return ('value 1') }
# if (<condition 2>) { return ('value 2') }
# if (<condition 3>) { return ('value 3') }
#
# but it's cleaner, and you can make each Command much more complex
# than the body of a sensible conditional.
###
## STATE-SPECIFIC OPERATIONS
## _get_commands (nil) : listref
#
# each Machine has its own list of Commands that should be
# executed in response to the user's input. this routine returns
# a reference to that list.
#
sub _get_commands {
return ([]);
}
1;
This code comes from a larger project, where the parameter $model was itself an object. The Model was responsible for all the data in the program, and the Commands simply called sets of Model methods.
| [reply] [Watch: Dir/Any] [d/l] [select] |
> Yes, there are times when there are much more elegant solutions
> then nested if-elses, but shouldn't the goal be simplicity over
> a blanket condemnation? I guess I'm just not seeing the why in
> "Why I Hate Nested If-Else blocks."
A series of nested conditionals forms a state machine. Every block is its own state, and every test marks a transition from one state to the next:
if ($a) {
if ($b) {
&S1;
} else {
&S2;
}
} else {
if ($c) {
&S3;
} else {
&S4;
}
}
is equivalent to:
+-----(b)->[S1]--+
| |
+-----(a)->[test b]--+ |--+
| | | |
| +-(not-b)->[S2]--+ |
[test a]--| |-->[end]
| +-----(c)->[S3]--+ |
| | | |
+-(not-a)->[test c]--+ |--+
| |
+-(not-c)->[S4]--+
Nested conditionals work well if the machine you're building graphs out to a simply-connected binary tree, like the one above, but they become less desirable as your machine grows more complex.
Basically, the problem boils down to representing arbitrary data structures with a binary tree. There are some things you just can't do directly, like forming complex connections:
+-----(b)->[S1]-+
| |
+-----(a)->[test b]-+ +---->[S5]-+
| | | |
| +-(not-b)->[S2]---+ |
[test a]-+ | | +->[end]
| | | |
| +-----(c)->[S3]-+ | |
| | +-->[S6]-+
+-(not-a)->[test c]-+ |
| |
+-(not-c)->[S4]---+
So you have to simulate the connections by duplicating nodes:
+-----(b)->[S1]->[S5]-+
| |
+-----(a)->[test b]--+ |--+
| | | |
| +-(not-b)->[S2]->[S6]-+ |
[test a]--| |-->[end]
| +-----(c)->[S3]->[S5]-+ |
| | | |
+-(not-a)->[test c]--+ |--+
| |
+-(not-c)->[S4]->[S6]-+
Which introduces synchronization problems.
The more complicated your machine is, the harder you have to twist it around to fit the binary-tree model of nested conditionals. And the more you twist, the harder it is to figure out what the original machine looked like while you're reading the code.
In fact, since programmers often evolve code instead of designing it, I'd give strong odds that even the programmer who writes a series of nested conditionals doesn't know what kind of machine he's building, and can't prove that it's a well-formed minimal solution to the problem at hand.
So it's not that nested conditionals are inherently evil. They're quite useful when applied properly. So are gotos. And like gotos, nested conditionals give programmers a way to disguise sloppy or inconsistent thinking as complex control flow. In other words, they can make code unnecessarily complex while looking perfectly reasonable every step of the way. That's why we should use them carefully and examine them critically, not just accept them blindly.
| [reply] [Watch: Dir/Any] [d/l] [select] |
I've been following this thread with some interest, as I just finished writing a CGI with a very unwieldy set of if / elsif / else statements, and I'm interested in how to put it on a more rational footing (posted below for anyone who wants a laugh). In simpler situations I've used a dispatch table. But here I couldn't work out how to pass (the right) arguments. As far as I can see, this is not handled explicitly above. I'd be interested in how to deal with the need (A) to pass different arguments to different subs; and (B)to pass different args to the *same* sub under different conditions ?
My baobab-style if tree, so we can all see what I'm up against:
if ($g{'Action'} eq 'MainPage') {
MainPage($Persist, $UserName);
}
if (($g{'Action'} eq 'Course') or ($g{'Action'} eq 'EditCourse'))
+{
$g{'CourseID'} = GetNewCourse() unless defined $g{'CourseID'};
UpdateTempData($g{'CourseID'});
EditCourse($Persist, $g{'CourseID'}, $g{'Return'});
}
elsif ($g{'Action'} eq 'Create Course') {
my $CourseID = GetNewCourse($UserName);
UpdateTempData($CourseID);
EditCourse($Persist, $CourseID, $g{'Return'});
}
elsif ($g{'Action'} eq 'EditEvent') {
EditEvent($Persist, $g{'CourseID'}, $g{'Return'});
}
elsif ($g{'Action'} eq 'New Venue') {
my $VenueID = GetNewVenue($Persist,$UserName);
EditVenue($Persist, $VenueID, $g{'Return'});
}
elsif (($g{'Action'} eq 'Venue') or ($g{'Action'} eq 'EditVenue'))
+ {
EditVenue($Persist, $g{'VenueID'}, $g{'Return'});
}
elsif ($g{'Action'} eq 'Course Overview') {
CourseView($Persist, $UserName);
}
elsif ($g{'Action'} eq 'Venue Overview') {
VenueView($Persist,$UserName);
}
elsif ($g{'Action'} eq 'DeleteCourse') {
DeleteCourse($Persist, $g{'CourseID'}, $g{'Return'});
}
elsif ($g{'Action'} eq 'Delete Course') {
DeleteCourseYes($Persist, $g{'CourseID'}, $g{'Return'});
if ($g{'Return'} eq 'CourseView') {
CourseView($Persist, $UserName);
}
else {
MainPage($Persist, $UserName);
}
}
elsif ($g{'Action'} eq 'Keep Course') {
if ($g{'Return'} eq 'CourseView') {
CourseView($Persist, $UserName);
}
else {
MainPage($Persist, $UserName);
}
}
elsif ($g{'Action'} eq 'DeleteEvent') {
DeleteEvent( $Persist, $g{'EventID'}, $g{'Return'});
}
elsif ($g{'Action'} eq 'Delete Event') {
DeleteEventYes( $Persist, $g{'EventID'});
if ($g{'Return'} eq 'CourseView') {
CourseView($Persist, $UserName);
}
elsif ($g{'Return'} eq 'EditEvent') {
EditEvent($Persist, $g{'CourseID'},0,$g{'CourseTitle'});
}
else {
MainPage($Persist, $UserName);
}
}
elsif ($g{'Action'} eq 'Keep Event') {
if ($g{'Return'} eq 'CourseView') {
CourseView($Persist, $UserName);
}
elsif ($g{'Return'} eq 'EditEvent') {
EditEvent($Persist, $g{'CourseID'},0,$g{'CourseTitle'});
}
else {
MainPage($Persist, $UserName);
}
}
elsif ($g{'Action'} eq 'DeleteVenue') {
DeleteVenue($Persist, $g{'VenueID'}, $g{'Return'});
}
elsif ($g{'Action'} eq 'Delete Venue') {
DeleteVenueYes($Persist, $g{'VenueID'}, $g{'Return'});
if ($g{'Return'} eq 'VenueView') {
VenueView($Persist, $UserName);
}
else {
MainPage($Persist, $UserName);
}
}
elsif ($g{'Action'} eq 'Keep Venue') {
if ($g{'Return'} eq 'VenueView') {
VenueView($Persist, $UserName);
}
else {
MainPage($Persist, $UserName);
}
}
elsif ($g{'Action'} eq 'Save Venue') {
if (my $Errors = SaveVenue($Persist, $UserName)) {
EditVenue($Persist, $g{'VenueID'}, $g{'Return'}, $Errors);
}
else {
WriteVenue();
if ($g{'Return'} eq 'ReturnToEditEvent') {
SaveVenue($Persist, $UserName);
EditEvent($Persist, $g{'CourseID'}, $g{'Return'},$g{'C
+ourseTitle'},0);
}
elsif ($g{'Return'} eq 'VenueView') {
SaveVenue($Persist, $UserName);
VenueView($Persist, $UserName);
}
else {
SaveVenue($Persist, $UserName);
MainPage($Persist, $UserName);
}
}
}
elsif ($g{'Action'} eq 'More Keywords') {
EditCourse($Persist, $g{'CourseID'}, $g{'Return'});
}
elsif ($g{'Action'} eq 'Next Step') {
if (my @Errors = CourseErrorCheck()) {
EditCourse($Persist, $g{'CourseID'}, $g{'Return'}, \@Error
+s);
}
elsif (my $OldTitle = TitleCheck()) {
UpdateTempData($g{'CourseID'});
QueryTitle($Persist, $g{'CourseID'}, $g{'Return'}, $OldTit
+le);
}
else {
UpdateTempData($g{'CourseID'});
EditCourseInfo($Persist, $g{'CourseID'}, $g{'Return'});
}
}
elsif ($g{'Action'} eq 'New Course') {
my $g = GetFromFile($g{'CourseID'},\%g);
%g = %$g;
DestroyTempFile($g{'CourseID'});
$g{'CourseID'} = GetNewCourse();
MakeTempFile($g{'CourseID'});
UpdateTempData($g{'CourseID'});
EditCourseInfo($Persist, $g{'CourseID'}, $g{'Return'});
}
elsif ($g{'Action'} eq 'Change Name') {
UpdateTempData($g{'CourseID'});
EditCourseInfo($Persist, $g{'CourseID'}, $g{'Return'});
}
elsif ($g{'Action'} eq 'More Links') {
UpdateTempData($g{'CourseID'});
EditCourseInfo($Persist, $g{'CourseID'}, $g{'Return'});
}
elsif ($g{'Action'} eq 'Another Page') {
SaveUserPage($Persist, $g{'CourseID'},$g{'PageTitle'},$g{'Page
+Text'},$g{'WeFormat'},$g{'CurrentPage'});
$g{'PageTitle'} = undef;
$g{'PageText'} = undef;
EditCourseInfo($Persist, $g{'CourseID'}, $g{'Return'},0,1);
}
elsif ($g{'Action'} =~ /^Edit Page (\d*)$/) {
SaveUserPage($Persist, $g{'CourseID'},$g{'PageTitle'},$g{'Page
+Text'},$g{'WeFormat'},$g{'CurrentPage'});
EditCourseInfo($Persist, $g{'CourseID'}, $g{'Return'}, $g{"Pag
+eID_$1"},1);
}
elsif ($g{'Action'} =~ /^Delete Page (\d*)$/) {
UpdateTempData($g{'CourseID'});
SaveUserPage($Persist, $g{'CourseID'},$g{'PageTitle'},$g{'Page
+Text'},$g{'WeFormat'},$g{'CurrentPage'});
QueryDeleteUserPage($Persist, $g{'CourseID'}, $g{'Return'},$g{
+"PageID_$1"},$g{'CurrentPage'});
}
elsif ($g{'Action'} eq 'Yes, Delete Page') {
DeleteUserPage($g{'PageID'});
UpdateTempData($g{'CourseID'});
EditCourseInfo($Persist, $g{'CourseID'}, $g{'Return'},$g{'Curr
+entPage'},1);
}
elsif ($g{'Action'} eq 'No, Keep Page') {
UpdateTempData($g{'CourseID'});
EditCourseInfo($Persist, $g{'CourseID'}, $g{'Return'},$g{'Curr
+entPage'},1);
}
elsif ($g{'Action'} eq 'No, Keep Page') {
UpdateTempData($g{'CourseID'});
EditCourseInfo($Persist, $g{'CourseID'}, $g{'Return'},$g{'Curr
+entPage'},1);
}
elsif ($g{'Action'} eq 'Proceed') {
SaveUserPage($Persist, $g{'CourseID'},$g{'PageTitle'},$g{'Page
+Text'},$g{'WeFormat'},$g{'CurrentPage'});
UpdateTempData($g{'CourseID'});
if (my $TearSheetError = CourseInfoErrorCheck()) {
EditCourseInfo($Persist, $g{'CourseID'}, $g{'Return'},0,0,
+$TearSheetError);
}
else {
EditEvent($Persist, $g{'CourseID'}, $g{'Return'},$g{'Cours
+eTitle'},0);
}
}
elsif ($g{'Action'} eq 'Save Course') {
SaveUserPage($Persist, $g{'CourseID'},$g{'PageTitle'},$g{'Page
+Text'},$g{'WeFormat'},$g{'CurrentPage'});
UpdateTempData($g{'CourseID'});
if (my $TearSheetError = CourseInfoErrorCheck()) {
EditCourseInfo($Persist, $g{'CourseID'}, $g{'Return'},0,0,
+$TearSheetError);
}
else {
SaveCourse($Persist, $g{'CourseID'}, $g{'Return'});
if ($g{'Return'} eq 'CourseView') {
CourseView($Persist, $UserName);
}
else {
MainPage($Persist, $UserName);
}
}
}
elsif ($g{'Action'} eq 'Make Venue') {
my $VenueID = GetNewVenue($Persist,$UserName);
EditVenue($Persist, $VenueID,'ReturnToEditEvent',0,$g{'CourseI
+D'},$g{'CourseTitle'});
}
elsif ($g{'Action'} eq 'Add Event') {
if (my $Errors = CheckEvent($g{'CourseID'})) {
EditEvent($Persist, $g{'CourseID'}, $g{'Return'},$g{'Cours
+eTitle'},$Errors);
}
else {
AddEvent($Persist, $g{'CourseID'}, $g{'CourseTitle'});
EditEvent($Persist, $g{'CourseID'}, $g{'Return'},$g{'Cours
+eTitle'},0);
}
}
elsif ($g{'Action'} eq 'Save All') {
my $Errors = CheckEvent($g{'CourseID'});
my $DateError = 0;
my $VenueError = 0;
my $DuplicateError = 0;
if ($Errors) {
$DateError = 1 if grep {$_ eq 'Date'} @$Errors;
$VenueError = 1 if grep {$_ eq 'Venue'} @$Errors;
$DuplicateError = 1 if grep {$_ eq 'Duplicate'} @$Errors;
}
if ($DateError + $VenueError == 1) {
EditEvent($Persist, $g{'CourseID'}, $g{'Return'},$g{'Cours
+eTitle'},$Errors);
}
else {
AddEvent($Persist, $g{'CourseID'}, $g{'CourseTitle'}) unle
+ss ($DuplicateError == 1 or $DateError + $VenueError == 2);
if (stat "$filepath/tempfiles/$g{'CourseID'}") {
UpdateTempData($g{'CourseID'});
SaveCourse($Persist, $g{'CourseID'}, $g{'Return'});
}
if (defined $g{'Return'} and $g{'Return'} eq 'CourseView')
+ {
CourseView($Persist, $UserName);
}
else {
MainPage($Persist, $UserName);
}
}
}
else {
MainPage($Persist, $UserName, $UserCookie);
}
§ George Sherston | [reply] [Watch: Dir/Any] [d/l] |