Published on

The Curse of Null


One of the most irritating things to deal with in programming is the proper handling of nulls. The creator of null Tony Hoare laments describing it as his "... billion dollar mistake..." due to all the potential mistakes, system errors and vulnerabilities it can cause.

Kotlin goes a long way in helping manage nulls better but it still has to be interoperable with Java forcing it to be a part of the language. Today I came across one of these not so obvious bugs caused by having a nullable variable. I had an enum similar to the below:

enum class ActiveState {

I then had a bean that used this but had it as nullable which was later used in an if statement:

data class LightFitting(val activeState: ActiveState?, val brand: String)


//in some other class
if(fitting.activeState == ActiveState.ON) {
// thing to do if on
} else {
// thing to do if off

It's glaringly obvious if you look at the above that the null case was not dealt with. This was a contrived example but in my actual code this issue resulted in a downstream process not behaving as expected which made this bug much harder to find.

A way to fix the symptom of this issue is to add an explicit check for null and handle that. But ideally we should be dealing with the root of the cause instead of trying to fix the symptom of it. The better (yet not always easy way) is to make this variable not nullable in the data class where it is declared. This will result in all current downstream processes being less buggy and all future processes also being less erroneous when using our bean.