Well I agree that efficiency of execution is *not* a significant concern 80% of time (results of independent research conducted at the freaky laboratories). However, well written code is self documenting code. This includes things like giving variables meaningful names that relate the the data they represent. It also means chosing the appropriate control structure that best represents the type of logic you, the programmer, have in mind.
For example, there several ways you could iterate through an array that are all technically feasable:
Example 1: the traditional approach to traversing an array in many languages
PHP Code:
$myArray = {0, 1, 2, 3, 4, 5};
$count = count($myArray);
for($i = 0; $i < $count; $ i++) {
echo $myArray[$i];
}
Example 2: technically valid but more obscure way of doing the same thing (harder to glean the logic on first reading).
PHP Code:
$myArray = {0, 1, 2, 3, 4, 5};
while(! empty($myArray[$i])) {
echo $myArray[$i++];
}
But the cleanest, most lucid way of writing this (IMHO) because it is self documenting (the code clearly explains the programmers thinking):
PHP Code:
$myArray = {0, 1, 2, 3, 4, 5};
foreach($myArray AS $element) {
echo $element;
}
As others have stated already, on top of the fact that it is easier to format and read a switch structure over a long if/elseif/else stucture. However, the point I was getting at with my code above is that there are times when the switch control structure illustrates the purpose of the code and the architecture of the script. Skunk's example is the classic example of creating a switchboard architecture. See http://www.fusebox.org/. They call their architecture fusebox, but I think that the metaphore of a switchboard is more suitable. I have been working on a member control panel for a site and the switchboard architecture is perfect for this. Here is a pseudo-mumbo-jumbo explaination (hehe - the last time I wrote pseudo-mumbo-jumbo, no one understood what I was going on about):
Code:
IF the user's session is not valid THEN
redirect user to login page
EXIT the script
END IF
include the file with the member control panel header and navigation html
SWITCH ON HTTP_GET_VARS[action]
CASE OF "foo"
include file "dofoo.php"
break
CASE OF "bar"
include file "dobar.php"
break
DEFAULT ACTION
include file "default.php"
END SWITCH
include the file with the member contol panel footer html
EXIT
So hopefully not only is the code I would write to impliment that design neat and readable, but it reflects the architecture of the member control panel application. The control panel pages are generated by sending all requests through a index.php which acts as a switchboard. The designer can also, hopefully, follow the logic of the application and see how his/her client side code will fit in. So hopefully it is a clean architecture for all parties to follow.
Bookmarks