Nullable!T with T of class type

Jonathan M Davis newsgroup.d at jmdavisprog.com
Mon Jun 25 22:58:41 UTC 2018


On Monday, June 25, 2018 19:40:30 kdevel via Digitalmars-d-learn wrote:
> Just stumbled over the following design:
>
>     class S {...}
>
>     class R {
>
>        Nullable!S s;
>
>     }
>
> s was checked in code like
>
>     R r;
>
>     if (r.s is null)
>        throw new Exception ("some error message");
>
> At runtime the following was caught:
>
>      fatal error: caught Throwable: Called `get' on null Nullable!S
>
> Why can't this programming error be detected at compile time?

If you have a function that accepts Nullable!T, when that function is
called, how on earth is it going to know whether the argument it received
was null at compile time? That depends entirely on the argument, which could
have come from anywhere. So, in the general case, the compiler can't
possibly determine whether a variable is null or not at compile time.

And as far as just within a function goes, Nullable is a library type.
There's nothing special about it. The compiler has no magic knowledge about
what it does or how it functions. So, how would it know that

R r;
r.foo();

was bad code? And honestly, this sort of problem actually gets surprisingly
thorny even if you tried to bake this into the compiler for a built-in type.
Sure, it would be straightforward for the compiler to see that

int* i;
*i = 42;

is dereferencing null, but as soon as you start adding if statements,
function calls, etc. it quickly becomes impossible for the compiler to
accurately determine whether the pointer is null or not. Any such attempt
will inevitably end up with false positives, forcing you to do stuff like
assign variables values when you know that it's unnecessary - it would
complicate the compiler considerably to even make the attempt. It's far
simpler to just treat it as a runtime error. Even more restricted languages
such as Java do that. Java does try to force you to initialize stuff
(resulting in annoying false positives at times), but in general, it still
can't guarantee when a variable is null or not and is forced to insert
runtime null checks.

> Is it possible
> to "lower" the Nullable operations if T is a class type such that
> there
> is only one level of nullification?

It's been discussed before, but doing so would make the behavior of Nullable
depend subtly on what type it contained and risks bugs in generic code.
Also, there _is_ code out there which depends on the fact that you can have
a Nullable!MyClass where the variable has a value and that value is a null
reference. If you really don't want the extra bool, then just don't use
Nullable. Class references are already naturally nullable.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list