Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save brettsantore/32f40f69ea4bbcf55417cf7758e9c049 to your computer and use it in GitHub Desktop.

Select an option

Save brettsantore/32f40f69ea4bbcf55417cf7758e9c049 to your computer and use it in GitHub Desktop.
Removing unnecessary else statements
The follwing code can be in many place, functions, methods, or a single page script.
I'd like to put these to pieces of code side by side, so you can have a look and hopefully we can agree,
the 2nd version is more readable.
The first example is a snippet that expects something to be true, and then acts on that assertion.
The code would work, but there is a hanging detail at the bottom, that I think should be cleaned up.
If the expectation was false, were going to enter the else protion, and do something there.
if($expectation == true) {
// Continue script exection
} else {
throw new \Exception();
}
It take a little more time to figure out the code and adds unnecesarry complexity when the expectation is false.
If in the second example, the only change is flipping the logic.
We check to see if our expection is incorrect, and handle that issue immediately.
Otherwise, we would continue execution as expected.
if($expectation == false) {
throw new \Exception();
}
// Continue script exection
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment