Do you abuse the null coalescing operator (and isset/empty as well)?

  1. Comments (2)

Since the null coalescing operator has been introduced in PHP7, one can find it almost everywhere. But I have a feeling that most of time it is rather an abuse than a fair use. And the same goes for isset()/empty() as well. Why? Let me explain myself.

Recently I've seen a lot of code like

if (empty($var)) { ...
// or
echo $var ?? '';
// and so on

And I grow to find that in most cases the null coalescing/empty() is used as rather a "shortcut" than a good practice. How can I tell that? Because its sole purpose here is to suppress a possible error.
Just think of it: you would gladly not use it, but you do, just due to possible Undefined variable/index error. So it is effectively used to suppress an error. But suppressing errors is a bad practice by itself!

Error messages are programmer's friends, not foes. They are intended to help a programmer to get a clue why their code doesn't work. Therefore errors shouldn't be suppressed. Even such a trifle error like "Undefined variable" which actually helps to find a typo in a variable's name.

Here is what I am talking about:

if (condition) {
    
$var 1;
}
// somewhere down below in the code
if (!empty($vaar)) {
    
// gets never executed due to a typo, but you'd never know why
}

vs.

$var null;
if (
condition) {
    
$var 1;
}
if (
$vaar) {
    
// we get an undefined variable error, and look up the name
}

That's why it is recommended to define a variable before use rather than checking for the existence/emptiness. Besides, always defining a variable also helps to make your program more organized, more predictable.

It's fair to use the null coalescing operator for the outside variables that could be not set. But for any internal variable it's better to avoid it, having a variable deliberately set instead.

Nowadays PHP is drifting towards being a much stricter language than it used to be, with all its strictly typing movement and I feel that having all variables defined before use is a step in the same direction.


Related articles: