Hacker News new | ask | show | jobs
by aindhaden 3485 days ago
I suspect we may be talking about two different approaches. Nobody _wants_ to trip on a null reference, naturally. But there are different ways of achieving that, and some of them yield additional benefits.

One way is to forbid them outright (which is what Tony Hoare regretted not doing when he made the "billion dollar mistake" presentation IIRC).

Allowing them to run unchecked is obviously not a good idea.

The "null object pattern" is another option, where the nulled var will be replaced on the fly with a "mock" that will not cause any trouble.

Here's another approach. It's more convoluted and you need the language to help you with it (Java does), but it return it offers the benefits described in my previous post:

* Implicit nulls across the board. * No penalty if the nulled variable is not used in an ambiguous manner (passing-on and checking the reference are ok). * Consistent runtime fail-fast behavior if the nulled variable is used in a manner that requires the declared type. (Java throws an exception, which uncaught leads to the stop of the program, thus preventing undefined behavior, but also allows the programmer to catch and recover.) * Most importantly: you DO NOT check for nulls with inline checks or assertions, but instead rely on unit tests to validate intended behavior.

The technique is called "passing nulls" in UT.

The end result is a more "relaxed" code, which promotes loose coupling and leads to more flexible code paths, which in turn make possible additional patterns. If you're not hurting anything by nulls why be forced to conform to rigid declarations? And if you are hurting something, then you will be forced to deal with it in a consistent manner.

1 comments

> Here's another approach. [...]

How is that different from the usual approach in Java, which exactly produces the problems observed?

Other languages, eg. Kotlin and now PHP enforce that variables and parameters that are declared to be not null are not null. Not null is the default behaviour. If you want nullable vars or params, then you have to declare it through `?`.