You can, and probably should, design with null
cases in mind. For example, in your problem domain, when does it make sense for class methods to return null
? When does it make sense to call functions with null
arguments?
Broadly speaking, it can be beneficial to remove null
references from code whenever possible. In other words, you can program to the invariant that "this will not be null here... or there". This has many benefits. You won't have to obfuscate code by wrapping methods in deref_or_throw
. You may achieve more semantic meaning from code, because, how often are things null
in the real world? Your code may be more readable if you use exceptions to indicate errors rather than null
values. And finally, you reduce the need for error-checking and also reduce the risk of run time errors (the dreaded null pointer dereference).
If your system was not designed with null
cases in mind, I'd say it's best to leave it alone and not go crazy wrapping everything with deref_or_throw
. Perhaps take an Agile approach. As you are coding, inspect the contracts that your class objects offer as services. How often can these contracts reasonably be expected to return null
? What is the semantic value of null
in these cases?
You could probably identify the classes in your system that might reasonably be expected to return null
. For these classes, null
may be valid business logic, rather than fringe cases that are indicative of implementation errors. For the classes that might be expected to return null
, the additional check may be worth the safety. In this sense, checking for null
feels more like business logic rather than low level implementation details. Across the board, though, systematically wrapping all pointer deference in deref_or_throw
might be a cure that is its own poison.