-
-
Save jsjohnst/1479655 to your computer and use it in GitHub Desktop.
<?php | |
if($http_code >= 200 && $http_code < 300) { | |
if($body == "foo") { | |
// do something | |
} else if($body == "bar") { | |
// get drunk | |
} else { | |
// do something else | |
} | |
if($body != "bar") { | |
// don't get drunk | |
} | |
} else if($http_code == 404) { | |
// not found? | |
} else if($http_code > 500) { | |
// throw an exception? | |
} else { | |
// handle default | |
} |
<?php | |
switch(true) { | |
case $http_code >= 200 && $http_code < 300: | |
if($body == "foo") { | |
// do something | |
} else if($body == "bar") { | |
// go drinking | |
break; | |
} else { | |
// do something else | |
} | |
// don't get drunk | |
break; | |
case $http_code == 404: | |
// not found? | |
break; | |
case $http_code > 500: | |
// throw an exception? | |
break; | |
default: | |
// handle default | |
break; | |
} |
The example was just using http code as it's a good example of ranges and conditionals.
Also, in dynamic languages, it's not a "misuse" and is something intentionally supported, especially in PHP/Ruby/Javascript.
I just mean that the switch is wasting an entire block level with "switch (true)", which is semantically useless. Personally, I only use switch for equality testing on a single expression.
The switch basically boils down to the if-elseif-else anyway, with a superfluous boolean:
if (true == ($http_code >= 200 && $http_code < 300)) {
...
} else if (true == ($http_code == 400)) {
...
} etc...
Then the answer becomes obvious that the first method was the best option.
You're right that it's a valid statement, but it's an unusual use of switch, which by virtue is less readable and maintainable.
I would say the if-elseif-else is better. The switch statement is a bit of a misuse. If the HTTP code wasn't in certain ranges, then the switch would be better:
switch ($http_code) {
case 200:
...
case 300:
...
case 404:
...
case 500:
...
default:
...
}