The Zero-NULL game means that if 0 or NULL is used incorrectly then everyone loses.
At every place I worked discussions or issues with 0 and NULL always popup. This is because there are some confusions with this. Not everyone knows the rules about the Zero-NULL game. That’s why it’s my purpose here to explain it in some short rules that are easy to remember and follow.
Rule 1: Zero or NULL
The first rule of the game is to call it zero or NULL. Everything starts with good communication. If both are pronounced the same, then no distinction can be made. Your are already lost when breaking this rule.
Rule 2: NULL indicates no value
The second rule is that NULL indicates no value. Thus it means there is no value. Never use NULL to indicate zero values.
Rule 3: 0 indicates an integer value
The third rule is that zero always indicates the actual value of 0 or in case of Boolean this means FALSE. Thus zero is the value 0 or false. Never use it to indicate there is no value. If you have a index field in your database. Don’t use 0 when you mean that there is no linked value. You need to use NULL, this is also a requirements when correctly using foreign keys.
Rule 4: Declare NOT NULL
The fourth rule is to declare in our database if NULL is possible or not. We should always use NULL and not 0 to indicate a none existing value. If there always needs to be a value then we should declare the column to be NOT NULL. Don’t allow values in your database that are impossible to occur. This way you don’t need to take into account the edge case that someone manual changes the database value to NULL.
BONUS information for PHP
Good to know when working with 0 or NULL:
- ” and 0 are considered FALSE in a boolean context (” == 0). But a good practice is to always use the strict equal operator === instead. In that case we also check the types of the values when comparing.
- empty() only checks if the argument is boolean FALSE. It makes no difference between ”, 0 or NULL.
- is_null() actually checks if the variable is NULL
- When checking if a variable is NULL the recommended way is to use if ($variable !== NULL). This has the same functionality as is_null() but is faster because its not a method call.
- isset() just checks if the variable is not NULL
- if ($variable) just checks if its FALSE or TRUE. This means ”, 0 or NULL are considered as true.
Even if you already mastered this knowledge. I think this is an easy and effective way to explain the differences about 0 and NULL to developers that need a quick refresh. These rules are simple but so important. In some cases the wrong use of this causes a lot of code smell or structures that cost a lot of refactoring and testing to fix. Bookmark this page and share it the next time you see someone trying to play the Zero-NULL game. When you don’t know the rules, then not only you but your whole team will lose.