sharf
sharf

Reputation: 2143

Is it good practice to ignore non-fatal errors?

When I learned PHP I was taught to make my code error free, but to still hide errors in production code to ensure a clean user experience.

I've recently been involved in some projects where the original writer took the approach of leaving in errors and warnings and even utilizing them to achieve something, rather than write code without it.

For example, the code would look like this:

$numm = 0;
while($numm < 10){
    $var = "something,".$var;
    $numm++;
}

This code will throw a non-fatal Noticethe first time through the loop, because $var doesn't exist for the first concatenation.

There are tons of other examples where they either ignore errors, or even utilize them (to end loops, etc.) but then hide them from the user.

To me, this seems like bad practice, but I could just be OCD.

Upvotes: 0

Views: 184

Answers (3)

Zia
Zia

Reputation: 2710

One thing that I have always found annoying was doing things like:

$var = isset($var) ? "something,".$var : "something,";

This one liner will prevent the error but not ideal way of doing it when you consider the number of possible uses. Imagine an associative array that returns that doesn't always have all it's key/values you would expect set.

One approach that i take to nearly all my apps is creating and using the following function:

function rtnVal(&$val, $default = null){
    return isset($val) ? $val : $default;
}

so in this case, all I have to do is this:

$var = "something,".rtnVal($var);

Easy ain't it? In case you didn't know, defining

function rtnVal(&$var) { ... }

instead of:

function rtnVal($var) { ... }

(notice the & symbol) means that $var is a 'placeholder' (passed by reference) and not actually passed. So when you use it, it doesn't have to be previously set.

There is one limitation to this though and that's working with Objects, they don't like being passed by reference this way so for those, I have yet to find a better solution.

Upvotes: 0

Alister Bulman
Alister Bulman

Reputation: 35169

A Notice is a bug waiting to happen. I routinely run development with error_reporting(E_ALL); set. I want to find the bugs before they are a problem, and not simply ignore the problems, potential, or not.

Upvotes: 5

a coder
a coder

Reputation: 544

Set a requirement of isset($var) in the while loop.

Upvotes: 0

Related Questions