Current sentiment on Nullable.get

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sat Dec 15 03:53:57 UTC 2018


On Friday, December 14, 2018 8:41:49 PM MST Neia Neutuladh via Digitalmars-d 
wrote:
> On Sat, 15 Dec 2018 03:01:18 +0000, Rubn wrote:
> > On Saturday, 15 December 2018 at 02:14:15 UTC, Jonathan M Davis wrote:
> >> n = value;
> >> foo(n.get);
> >
> > Why wouldn't you just do
> >
> > foo( value );
> >
> > then ? If you know the value isn't going to be null then you shouldn't
> > be using nullable.
>
> You don't know that cast(Object)null is an invalid value. You need to
> check whether you currently have a valid value. So you create a wrapper
> struct that has a sentry value. You know for certain that that sentry
> value doesn't conflict with anything the user might want to use (unlike,
> say, T.init).
>
> This lets you organize your code in a nicer way when you have complex
> initialization, or when you need to de-initialize a value.
>
> I mentioned it in the named arguments thread as a way to check whether all
> required parameters to a function were provided via an argument struct.
> Whether explicitly passing null is valid or not depends on the function,
> and the Invoker wrapper can't make that call. Whether an argument must be
> provided depends on the function signature alone. So the Invoker wrapper
> could use Nullable to distinguish between an argument that is absent and
> an argument that is present and equal to its type's .init value.

Exactly. Right now, generic code can be written that is able to use Nullable
to store a value and treat null as a valid value. Plenty of code does treat
null as an invalid value, but not all code does, and in that situation,
there is a difference between null and not having a value. You can write
generic code that does not care one whit what type it's operating on that
uses Nullable, whereas if Nullable treated pointers differently, that code
would have to be special-cased for pointers in able to function properly.

Having Nullable treat pointers differently results in a type that's
essentially worthless for anything other than value types (including generic
code). If the code isn't generic, then Nullable!(T*) is then the same as T*
but with different syntax, making it pointless. And if the code is generic,
then you end up with subtle bugs (and potentially crashes) due to Nullable
behaving differently for different types.

- Jonathan M Davis





More information about the Digitalmars-d mailing list