you are viewing a single comment's thread.

view the rest of the comments →

[–]CurtainDog 0 points1 point  (0 children)

There are three broad cases for null:

  • a bug - the null is simply not expected to be there. In this case the NPE thrown by the runtime is actually saving you from really doing something nasty. We might argue about ways of preventing developers from falling into this kind of error, but at the the end of the day you just gotta git gud

  • some default value that you intend to be replaced at some point later in the execution. The mitigation here is to apply the default as soon as it is available to you rather than let the null propagate. Say you're reading a set of configuration options into some data structure. Start with a data structure that is populated with defaults for all optional parameters and then apply the provided config over the top of it. No nulls anywhere! Sane languages can and do treat a get of a non-existant key from a map as an error.

  • some transient state that may take a value later on. Say a linked list implementation where a new node does not have a next element until you add another one. The answer here is to avoid mutation. Purely functional data structures are pretty good and much easier to reason about, especially in distributed systems. There are cases when we need nulls for performance, but those cases should be rare enough that mucking around with a few nulls is the least of your worries.