While working on some code recently, I noticed a preponderance — neigh, an outright overabundance — of swith/case logic blocks to control content.  What’s worse is that the input variable to the switch block happened to be the value of a specific hash key, which got me to thinking — what is the purpose of a switch/case block, after all?

As visions of data structures danced through my head, I became frustrated by constructs like the following:

echo <<<EOT
<div class="widget">
<p>Please select a value from the following list:</p>
<select name="selector">
EOT;
switch( $inputs['SID'] ) {
    case 'first':
        echo <<<EOT
<option value="one">First Value</option>
<option valyue="two">Second Value</option>
EOT;
        break;
    case 'second':
        echo <<<EOT
<option value="alpha">Alpha</option>
<option value="beta">Beta</option>
EOT;
        break;
    default:
        echo <<<EOT
<option value="start">Start Here</option>
<option value="end">End Somewhere Else</option>
EOT;
        break;
}

echo <<<EOT
</select>
</div>
EOT;

Now, I ask myself, why are we subjecting ourselves to this pain and misery?  The senseless use of the switch/case block in this context means that every time we add a new possibility for the value of $inputs['SID'] we must update our code.  Indeed, we must change every single location where $inputs['SID'] is ever referenced!  My proposal would seem to be a fair bit more elegant — use a hash to contain the contextual configuration throughout the codebase.  Say, something as simple as this:

$sids = array(
        'first' => array(
                'list' => array(
                        'first' => 'First Value',
                        'second' => 'Second Value',
                    );
            );
        'second' => array(
                'list' => array(
                        'alpha' => 'Alpha',
                        'beta' => 'Beta',
                    );
            );
    );

As thus, you can easily develop your tree as deeply as necessary, and from such useful sources as XML files and databases.  Once developed, your output block becomes as simple as:

echo <<<EOT
<div class="widget">
<p>Please select a value from the following list:</p>
<select name="selector">
EOT;

foreach( $sids[$inputs['SID']] as $k => $v )
{
    echo <<<EOT
<option value="$k">$v</option>
EOT;
}

echo <<<EOT
</select>
</div>
EOT;

Not the best example, nor the best code, but it illustrates the point.  Now we have one source for the construction of our $sids hash, and we don’t need to go digging through our code looking for all of the places we switch on $inputs['SID'] to figure out what content needs updating…

…the other beauty here is that we can remove all of the HTML from the code entirely, and instead place it in an external template file, and write a simple preprocessor that will find specific types of template placeholders and build the rest dynamically.  One file, one function, one data structure — nearly infinite dynamism.