You Must Not Admit a Single Null!

Jul 2, 2018
-
3
minute read

There are some principles in software development that offer benefits anywhere they are used, even in just some parts of the code. For others, they must be applied everywhere to be useful. The rule against never passing null must be applied everywhere for one major reason.

Most programmers generally know about the problemswithnull. But many still think, “I can be generally against null, and still make some exceptions here and there.”

For nulls, this thinking is entirely wrong!

With many of the principles of SOLID, Clean Code, and Elegant Objects, the benefits can be gained even if only a portion of the codebase uses it. If some methods are readable, and others aren’t, the codebase won’t naturally become more unreadable. If some classes are designed to handle only one use case, and some classes are giant classes of death, the codebase won’t necessarily trend towards large uncohesive classes. However, with null, it is a cancer that spreads to surrounding areas and starts to infect the whole codebase.

The reason is trust. Once trust is gone, the codebase begins to take another shape entirely.

Objects should Trust other Objects

Once the codebase starts accepting nulls, then as the team writes new classes and Objects, they no longer trust that they will receive valid, fully-formed Objects. This ruins developer trust in the codebase, and leads to defensive programming styles, which are wasteful and verbose. Then you will find null checks and null-coalescing operators start to appear in every constructor. The developers don’t trust the other developers, and so the Objects stop trusting other Objects.

The second problem is what allowing nulls into the code communicates. It starts with passing just a single optional parameter using null. Developers will think this is the correct pattern to emulate. Then you will find many classes in your codebase with ctors like this: