Adding the ?. null verification

H. S. Teoh via Digitalmars-d digitalmars-d at puremagic.com
Thu Jun 19 12:11:16 PDT 2014


On Thu, Jun 19, 2014 at 04:40:22PM +0100, Nick Treleaven via Digitalmars-d wrote:
> On 19/06/2014 16:04, H. S. Teoh via Digitalmars-d wrote:
> >we really should call it something else.  "failsafe" sounds a bit too
> >generic. What about "safeDeref" or just "deref"?
> 
> fallback? It could have an optional argument to override init.

I've thought about adding an optional argument to override init, but
unfortunately I can't think of a nice way to implement it. The problem
is that in order for the wrapper to work, it has to wrap around each
individual component of the dereferencing chain. So if you have a chain
like this:

	safeDeref(obj).subobj.prop.field.val

then the safeDeref wrapper only knows about obj, so it wouldn't know
what type .val is, because it can't tell beforehand which field you're
going to dereference next, and different fields may have different
types, nor where is the end of the chain. So it wouldn't know when to
return the specified default value.

As of now, I don't know of any way of passing the entire chain to
safeDeref without making it really ugly. Writing:

	safeDeref(obj.subobj.prop.field.val, defaultValue)

doesn't work because before the wrapper even gets invoked, you've
already dereferenced all the fields (and crashed on the null if there's
one in there). The only way I can think of to pass everything to the
wrapper is via a variadic list of alias parameters, but it looks very
ugly in practice:

	safeDeref!(defaultValue, obj, subobj, prop, field, val)

I've thought about having a penultimate wrapper in the chain:

	safeDeref(obj).subobj.prop.field.failsafe(defaultVal).val

But this doesn't work either for the same reason: failsafe() doesn't
know the next item in the chain will be .val (instead of, say, .length
which has a different type).

A possible compromise is:

	safeDeref(obj).subobj.prop.field.failsafe!val(defaultVal)

where the last element is passed as an alias to the failsafe template,
which then does the .init-replacement magic. It looks a lot uglier,
though. :-(


T

-- 
People demand freedom of speech to make up for the freedom of thought which they avoid. -- Soren Aabye Kierkegaard (1813-1855)


More information about the Digitalmars-d mailing list