Optional and orElse: design feedback/critique?
Paul Backus
snarwin at gmail.com
Sat Jul 27 15:07:56 UTC 2019
On Saturday, 27 July 2019 at 13:17:32 UTC, aliak wrote:
> * Null pointers are valid objects, so some!(int*)(null) is non
> empty
> * Null classses and interfaces are empty, so some!Class(null)
> is empty
I think it would be better to avoid weird special cases like
this. The optional package already includes a NotNull type, so
users can write `Optional!(NotNull!Class)` to opt into your
proposed semantics explicitly.
> orElse semantics:
> =================
>
> [...]
>
> So orElse works on a number of types and these are each types's
> semantics:
>
> * If T is a reference type, val1.orElse(val2) will return val1
> if (val1 !is null), else val2
> * If T is a range, the example above shows the semantics
> * If T is an Optional!U then it is treated separately in order
> to work with const Optional!U. The value returned by orElse is
> determined by the alternative value. If it is a U then
> optional.front will be returned, if it is an Optional!U then an
> optional will be returned. So the same semantics of range.
> * If T is Nullable!U, then isNull is checked. If it is false
> and alternative value is a U, then nullable.get is returned. If
> T is another Nullable, then the return type is a Nullable.
My first impression, upon reading this, is that I'm going to have
to refer to the documentation every time I use `orElse` in order
to be sure I'm doing it right. To me, this is a smell: if it
takes me this long to describe what ought to be a very simple
utility function, I can tell I've made it too complicated.
As far as concrete advice: the overloads for reference types and
ranges seem completely unrelated to Optional, so it seems like an
odd choice to include them in the "optional" package. The
overloads for Optional and Nullable make sense to include (though
the Nullable one really *ought* to be in Phobos), but
special-casing them to wrap the return value is too "magic" for
my tastes. Much better to just let people write
`some(val1.orElse(val2))` if that's what they want--it's only a
few more characters, and it makes it obvious at a glance what the
code is doing.
More information about the Digitalmars-d
mailing list