Languages are catching up to 2025 standards. From the decision to allow uninitialized class properties and variables, to today’s understanding that null is a deliberate developer’s decision (and a terrible one).
Even if you say “the programming language I use allows it to happen”, at least, most of the languages are implementing a kind of optional syntax to indicate this value.
“?” (question mark) is the most used type notation to defined that an object can be a disjoint union of null and the values of the actual type.
Other options have existed for long time know - but they only existed on smart languages and used only by smart people, and today are also becoming popular in many languages like Maybe type (or Optional depending on the language or package you use).
Here is a list of thing to look out before starting writing code…
Is null a valid value?
If null is valid, then everything is ok, otherwise I have to inform you that this is your fault.
We all know we cannot add null + 4. So we need to look how it happened.
Is this a callee problem?
Who calls the function is responsible for having valid data before calling a function, otherwise your entire code base is going to be performing unnecessary checks (defensive programming).
Are the defaults of the types right?
If you need to sum with the value and you have a null value in hands, you must know that if you convert null to zero, then we fix all the problems (
for sum 0 + 4 = 4, or for multiplication 1 * 4 = 4).
Can you use Option or Maybe type?
If you can use them, they are great options if you can build in a more pipeline style.
(true
? std::optional<int>(5)
: std::nullopt)
.and_then([](int value){
return value + 5
})
.value_or(5);
If std::nullopt is passed through the pipeline, then value_or will execute and 5 will be returned. If std::optional is passed, then the pipeline is executed and the result will be 10.
Depending on the language it can optimize this construction, but in most of the cases, any performance can be neglected. Measure always!
So…
This is enough for you to remember about default values and see a few options to not see anymore nulls on your code base.