ThomasK
ThomasK

Reputation: 2220

handeling errors in the if or else part?

I usually don't think about it, but I'm just curious if there's any reason to do it in one or the other part of the script?

Like:

if(empty($_POST['name'])){
    /*  handle the error  */
} else {
    /*  do something productive  */
}

or

if(!empty($_POST['name'])){
    /*  do something productive  */
} else {
    /*  handle the error  */
}

Like a script I'm working on now; First I need to check for empty required fields. After that I need to see if the provided name already exists or not. Then I need to make sure at least 1 ingredient is provided (for the recipe). If those checks out ok; I can continue to make sure each ingredient is available for the relation table. Finally I can add the actual recipe. After that I can add other associated stuff.

As you can see, I have a lot of if/else-statements going on. So back to my question; is it better take care of the errors at the top/beginning (if), or at the bottom/end (else)?

I might not be doing this error handling thing correct at all. Just came to think of the try/throw/catch-statements. But don't really know how those works...

Upvotes: 0

Views: 37

Answers (2)

Jayz7522
Jayz7522

Reputation: 334

As noted in other answers, it hardly matters; but, there are two factors which will theoretically affect computation time:

  • If the "if" condition is true, the else is skipped (as you likely know) saving some computation time. So, you'll have a faster average computational speed by putting the condition you expect to be true most often in the "if" condition.

  • This one is even more negligible, but theoretically true: "!" is an operator, and additional operations take additional time; so, avoiding an unnecessary use of "!" is preferable.

Upvotes: 2

Nick Coons
Nick Coons

Reputation: 3692

They are functionally the same, but my preference is for your second example where you handle the error ever else. The reason for this is because I like to have the expected/desired/non-error be what shows up first. I find that it makes the code more readable; someone following up on your code afterwards will have an easier time figuring out what you're wanting to accomplish.

Upvotes: 0

Related Questions