Introducing Nullable Reference Types in C#. Is there hope for D, too?
Dukc
ajieskola at gmail.com
Mon Nov 20 10:45:20 UTC 2017
On Sunday, 19 November 2017 at 04:04:04 UTC, Walter Bright wrote:
> Interestingly, `int` isn't nullable, and we routinely use
> rather ugly hacks to fake it being nullable, like reserving a
> bit pattern like 0, -1 or 0xDEADBEEF and calling it
> INVALID_VALUE, or carrying around some other separate flag that
> says if it is valid or not. These are often rich sources of
> bugs.
>
> As you can guess, I happen to like null, because there are no
> hidden bugs from pretending it is a valid value - you get an
> immediate program halt - rather than subtly corrupted results.
I don't deny these. Null is an excellent way to denote "empty" or
"invalid". Thats just what std.typecons.Nullable!T is for.
Granted, it is not quite as elegant as naturally nullable types.
But that does not mean nullables are always good. Consider:
struct TimeOfDay
{ byte hours
byte minutes
byte seconds
}
While it might make sense to make the TimeOfDay nullable as
whole, you definitely do not want all the fields have a null
value each. You know statically that if the struct is valid, then
all it's members are valid.
It would be only a performance slowdown to check for null with
them. You could skip those null-checks by convention but for sure
you would not always remember, causing sub-optimal performance.
Ideally you would want to leave it up to the type user whether
you have a null value or not, just like C# does. Whether it's
worth it's weight is a different question through.
About the question what should be default-initialized value for
an abstarct type were it non-nulllable, I think the type definer
should decide that. A library solution here would sound credible
to me. A type that wraps a reference type behaving like a value
type. Default initialized value and what to do on copy would be
passed as template parameters. Perhaps I should try...
More information about the Digitalmars-d
mailing list