Optional and orElse: design feedback/critique?
SimonN
eiderdaus at gmail.com
Sat Jul 27 17:01:14 UTC 2019
On Saturday, 27 July 2019 at 15:07:56 UTC, Paul Backus wrote:
> 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.
It's surprising that pointers and references are special-cased
differently, right.
But I suggest that null is the same as empty, both for pointers
and for references. I.e., the original post's proposal should
change its pointer semantics, some!(int*)(null) == no!(int*).
What was the original reason to treat pointers and class
references differently?
Reason to treat null as empty, always: We want at most one layer
of nullability/emptiness, and usually no nullability at all,
because we want to avoid nesting of "if it exists, do stuff,
otherwise do nothing". All possible nullability/emptiness should
be handled at once.
This usual case (at most one layer of nullability/emptiness)
should be quickest to write. If Optional!Class introduced
emptiness different from nullability, then
Optional!(NotNull!Class) would be standard usage because people
want at most one layer of emptiness, but then standard usage
would not be succinct.
I accept that Optional!(NotNull!Class) is more explicit, but this
is only because of D's lack of non-nullable references, which is
the problem in the first place. NotNull is an abstraction
inversion: It builds a non-nullable type (the less complex type
because it allows fewer values and is crash-free to call methods)
from a nullable type (which instead should be a sum type of the
nonexisting non-nullable type and empty).
I already use Optional!Class for single layer of nullability, and
Class for non-null by convention. 95 % of the time, I want
non-nullable. Exported methods, then, need in/out contracts to
check for non-nullability. These contracts should ideally be
inserted by the compiler on seeing a language-builtin
non-nullable reference.
-- Simon
More information about the Digitalmars-d
mailing list