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?
- MVC in simpler terms or the structure of a modern web-application
- How to get a single player's rank based on the score
- Articles
- Operator precedence or how does 'or die()' work.
- Why should I use prepared statements if escaping is safe?
- Numerical strings comparison
- Do generators really reduce the memory usage?
- How to make Stack Overflow a nice place
- Iterating over array getting look-ahead items along
- How to debug small PHP programs
Add a comment
Please refrain from sending spam or advertising of any sort.
Messages with hyperlinks will be pending for moderator's review.
Markdown is now supported:
>
before and an empty line after for a quote