Introducing Nullable Reference Types in C#. Is there hope for D, too?
Nick Treleaven
nick at geany.org
Mon Nov 20 19:13:53 UTC 2017
On Sunday, 19 November 2017 at 22:54:38 UTC, Walter Bright wrote:
> There's also an issue of how to derive a class from a base
> class.
If you want null, use a nullable type:
Base b = ...;
Derived? d = cast(Derived?) base;
if (d !is null) d.method;
> This implies one must know all the use cases of a type before
> designing it.
Start off with a non-nullable reference. If later you need null,
change to T?. T? is implicitly convertible to T where flow
analysis can tell that it is not null (e.g. after it is assigned
a non-nullable T).
>> It was your own design decision to hide the error.
>
> No, it was a bug. Nobody makes design decisions to insert bugs
> :-) The issue is how easy the bug is to have, and how difficult
> it would be to discover it.
The compiler would nag you when you try to dereference nullable
types, you have to act to confirm you didn't forget to check
null, a common mistake in reference heavy APIs.
>> No, it would have been better because you would have been used
>> to the more explicit system from the start and you would have
>> just written essentially the same code with a few more
>> compiler checks in those cases where they apply, and perhaps
>> you would have suffered a handful fewer null dereferences.
>
> I'm just not convinced of that.
Maybe you use nullable types a lot and rarely use references that
aren't meant to have null as a valid value. Most programmers have
plenty of statements where a reference is not supposed to be
null, and would appreciate having the compiler enforce this.
Popular new programming languages make nullable opt-in, not the
default, to reduce the surface area for null dereference bugs.
>> I'm not fighting for explicit nullable in D by the way.
>
> Thanks for clarifying that.
To avoid breaking existing code, there is a way however. We would
instead have a sigil (such as '$') for non-nullable references:
T nullable;
T$ nonNullable = new T;
typeof(new T) for full compatibility would still be T, but the
compiler would know it safely converts to T$.
More information about the Digitalmars-d
mailing list