Feedback on nulls in switch
Brian Goetz
brian.goetz at oracle.com
Mon Aug 10 18:45:13 UTC 2020
> More generally, I think this debate relates to others in records and
> Valhalla. It indicates to me that a more overarching story on nulls
> would be beneficial.
Indeed so. And in fact, this is exactly the motivation for the current
semantics; rather than extrapolating from the current ad-hoc nullity
behavior of `instanceof` and `switch`, the nullity behavior for pattern
matching is grounded in the principle that deconstruction is the inverse
of construction, and just as the language does not tell constructors
that they can't take null arguments or write nulls to fields, the
language should not be in the business of excluding nulls from binding
variables (or, for that matter, record fields or stream elements
or...) Of course we have to be compatible with the existing semantics
of these constructs, and this creates constraints and distortions, but
the motivation here is as you ask -- moving towards a more consistent
overall story. And that story is: nulls are OK to pass around, they
should only blow up when you dereference them.
I realize that by "something bigger" you probably meant non-nullable
types, and I get why you'd like that -- (just as you'd probably prefer
properties instead of records.) But that's far outside the scope of
Amber; that's major rocket surgery. Maybe in a future phase of Valhalla
we will be able to turn our attention on that.
> And if you took away nullable
> fields in records, much of the debate on nulls in pattern matching
> would simplify.
Not only do I think this sort of tinkering is a siren song in general,
but it wouldn't actually simplify anything (indeed, it makes things more
complicated), because the only thing special about records with respect
to pattern matching is that they come out of the box with a
deconstructor (just like they come with a constructor, equals, hashCode,
etc.) But just like constructors, equals, hashCode, etc, there's
nothing magic or record-specific about deconstructors, and all classes
will eventually be able to declare them. At which point an arbitrary
restriction on the domain of record fields does nothing to help pattern
matching -- it just makes records more complicated, and creates a new
asymmetry between records and classes.
This sort of tinkering often seems attractive, but is usually a
temptation best avoided, as it almost always ends up creating new sharp
edges for users to keep track of. In this case, it creates new
categories of classes that can't migrate to records.
The all-too-common idea that "nulls are bad so we should go out of our
way to outlaw them where we can" is a siren song; it usually just
creates impediments to refactorings that should work but subtly don't,
and burdens every developer with the need to be aware of every place
we've tried to patch away nullity, unsuccessfully.
More information about the amber-dev
mailing list