Reiterate total pattern accepting null in switch

Tagir Valeev amaembo at gmail.com
Mon Sep 6 09:12:50 UTC 2021


Hello!

Now, as we develop support in IntelliJ, we have a little bit of
experience with patterns in switches. So far, the thing I dislike the
most is that the total pattern matches null in the switch. I shared my
concerns before and now they are basically the same, probably even
stronger. Note that I'm not against total pattern matching null in
general (e.g., as a nested pattern in deconstruction). But I still
think that matching it at the top level of the switch is a mistake.
Mentally, the total pattern is close to the default case. It's just
more explicit and allows introducing a variable which could be
convenient if the selector expression is something complex, like a
method call. But the asymmetry in null handling adds confusion. Also,
adding a guard means that we do not receive null at this branch
anymore which is also confusing. E.g., `case Object obj` accepts null
but `case Object obj && obj != null` is meaningless as `obj != null`
is always true. Well, making the pattern non-total immediately
requires adding a default case, so you cannot just add a guard and do
nothing else. Still, it's mentally confusing:

switch(x) {
  ... other cases
  case Object obj -> ... // null goes here
}

switch(x) {
  ... other cases
  case Object obj && obj != null -> ... // exclude null
  default -> // add default, as compiler requests. Now only 'null' is
the remainder. But why it doesn't go here?
}

Finally, it complicates the automatic code analysis: to understand
whether a given switch throws NPE unconditionally, we need to resolve
all the pattern types and evaluate the type of selector expression.
This limits our ability for interprocedural analysis, as for
performance reasons, we can resolve references in the currently edited
file only.

I still think that only an explicit 'null' label should turn the
switch into null-friendly mode.

What do other experts think about this? Am I the only one who doesn't like this?

In general, I'm very positive about pattern matching in switches.
Aside from this nullability problem, everything else looks fine to me.

With best regards,
Tagir Valeev.


More information about the amber-spec-experts mailing list