Feedback: Using pattern context to make type patterns more consistent and manage nulls

John Rose john.r.rose at oracle.com
Mon Jan 25 04:20:23 UTC 2021


On Jan 24, 2021, at 4:46 PM, Stephen Colebourne <scolebourne at joda.org> wrote:
> 
> switch (box) {
>   case Box(Integer i) ...
>   case Box(Number n) ...
> }
> 
> Reading this code I have no way of knowing what it does. None.

That’s too hyperbolic.  We know 99% of what will happen even
if we are ignorant of the type of box.  So the details of what
happens with an expression sometimes depend on the precise
type of the expression.  That’s endemic to every statically
typed language, and not at all unique to this case, so it’s not
at all clear to me why you are pulling the emergency brake
at this point.  In short, I don’t buy it; I don’t even see how
I could begin to convince myself that you have a reasonable
point.  Sorry.

> If box is Box<Number> it does one thing. If box is Box<Object> it does
> something else. Sure the impact is only on null, but that is a
> secondary detail and not what is driving my concern. The key point is
> that someone reading the code can't tell what branch the code will
> take, and can get a different outcome for two identical patterns in
> different parts of the codebase.

At some point, there’s a burden on the writer of the code
to avoid what we affectionately call “puzzlers”.  As has been
said before, the existence of new puzzlers cannot be any
conclusive argument against a proposed language feature.

The burden, in this case, on the author of the switch statement,
is to gauge whether the handling of nulls and/or non-Number
boxed items is significant or not, and use the resources of the
language to communicate the policy of this switch towards
such values.  A separate default case, or a proposed “this is total”
marker on the final case, would do the job more than adequately.

— John




More information about the amber-dev mailing list