Skip to content

Instantly share code, notes, and snippets.

@jsjohnst
Created December 15, 2011 03:09
Show Gist options
  • Save jsjohnst/1479655 to your computer and use it in GitHub Desktop.
Save jsjohnst/1479655 to your computer and use it in GitHub Desktop.
Which is easier as far as code maintainability and readability goes?
<?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;
}
@rviscomi
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment