CleanCode logo
sitemap
SEARCH:
NAVIGATION: first page in sectionprevious pageup one levelnext pagefinal page in section

Guideline IF1: Avoid multiple if-then-else with jump table switching

For a choice of integers or other simple types which permit it, use a switch statement. For a choice of more complex data types (strings, etc.) use a jump table, allowing you to set up your selections during program initialization (possibly even in a configuration file!).

While Perl does not have an official switch statement, the perlsyn manual page, Basic BLOCKs and Switch Statements section, illustrates not one, not two, but nine different ways to achieve the same result. They are presented quite elegantly, so I won't repeat them here. At the very end of the section, it mentions, "You might also consider writing a hash of subroutine references instead of synthesizing a switch statement." But it does not provide such an example, so I've provided it here:

EXAMPLEPerl
Instead of:
	sub pick {
		my ($select, $val) = @_;
		if    ($select eq "abc") { doTaskA($val); }
		elsif ($select eq "def") { doTaskB($val); }
		elsif ($select eq "ghi") { doTaskC($val); }
		elsif ($select eq "jkl") { doTaskD($val); }
		elsif ($select eq "mno") { doTaskE($val); }
	}
	sub doTaskB { # stub for testing
		print "got value ".shift()."\n";
	}
	pick("def", 25); # test invocation
Use:
	my $JUMP_TABLE = {
		abc => \&doTaskA,
		def => \&doTaskB,
		ghi => \&doTaskC,
		jkl => \&doTaskD,
		mno => \&doTaskE
	};
	sub pick {
		my ($select, $val) = @_;
		&{$JUMP_TABLE->{$select}}($val);
	}
	sub doTaskB { # stub for testing
		print "got value ".shift()."\n";
	}
	pick("def", 25); # test invocation
Valid XHTML 1.0!Valid CSS!Get CleanCode at SourceForge.net. Fast, secure and Free Open Source software downloads
Copyright © 2001-2013 Michael Sorens • Contact usPrivacy Policy
Usage governed by Mozilla Public License 1.1 and CleanCode Courtesy License
CleanCode -- The Website for Clean DesignRevised 2013.06.30