Created
December 15, 2011 03:09
-
-
Save jsjohnst/1479655 to your computer and use it in GitHub Desktop.
Which is easier as far as code maintainability and readability goes?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} |
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
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.