Do you abuse the null coalescing operator (and isset/empty as well)?
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:
- Relative and absolute paths, in the file system and on the web server.
- PHP error reporting
- Do you really need to check for both isset() and empty() at the same time?
- What's wrong with popular articles telling you that foo is faster than bar?
- Articles
- Numerical strings comparison
- MVC in simpler terms or the structure of a modern web-application
- How to get a single player's rank based on the score
- Why should I use prepared statements if escaping is safe?
- Operator precedence or how does 'or die()' work.
- Do generators really reduce the memory usage?
- How to make Stack Overflow a nice place
- How to debug small PHP programs
- Iterating over array getting look-ahead items along
Comments:
Arno, the problem with
is that it doesn't test if $var is an array or if it exists at all. What if, due to an error somewhere, $var is another type or it doesn't exist at all? We will never know, it will silently return null. The proper code is (assuming strict typing):
but unfortunately it's much less readable. I really wish there was an operator that worked like ?? but worked only for an array as the left operand and throw an exception if the left operand was another type or didn't exist at all.
Thank you so much for your helpful instructions. This is the best website for php, pdo and mysql you can find! It helped to improve my coding a lot.
Well, to be fair, any modern IDE will tell you if you have an undefined variable.
But you are right about empty(). I believe it is due to php starting out as a duck-typed language and the lack of proper typing.
Consider: function test(SomeType $var): ?array { //... } This is a bad practice as one needs to both check for null and an empty array. If the function were to instead always output an array, the need for empty() goes away. Instead a simple: if ($var === []) is all that's needed.
Another one I see often is checking for null with empty(). Rather, the instanceof operator proves useful. if $foo = null|FooInterface then a simple ternary is sufiicient: $foo instanceof FooInterface ? 'Good' : 'Bad';
I sort of agree, but I am for letting programmers program. If they abuse the ?? operator to suppress error messages, then they are probably just inexperienced. I doubt that telling them not to use ?? will accelerate the learning process.
I do not find experienced programmers to typically do that. I very commonly use ?? to test for array indices, e.g. from outside input or where it just makes no sense to completely populate a sparse array just to avoid testing for empty. I find that too often people become dogmatic. I know the semantics of ?? and I know what I am doing. Oh, and just to kick a hornet's nest:
is semantically equivalent to
(the horror ;-)