break seen as a C archaism

Stephen Colebourne scolebourne at joda.org
Fri Mar 16 10:47:45 UTC 2018


On 16 March 2018 at 08:50, Peter Levart <peter.levart at gmail.com> wrote:
> I think that with introduction of e-switch, we might soon see it being
> "abused" for things like:
>
> doSomething(
>     par1,
>     switch (1) { case 1:
>         // compute result...
>        break resut;
>     },
>     par3
> );

The main use case where a block instead of an expression would be
useful in a method call is when calling super() in a constructor. So,
this is a valid use case.

> doSomething(
>     par1,
>     do {
>         // compute result...
>        break resut;
>     },
>     par3
> );

This is brilliant!!!! I played with some syntax choices last night but
they didn't really work. This one really does.

The proposal would be to add a new block expression to Java:

 do { <zero-to-many-statements>; break <expression>; }

This expression would be usable anywhere in Java that an expression
could be used today. ie.it is orthogonal to the switch discussion. The
new block expression would be immediately useful in constructor
super(), but there are no doubt other uses. The compiler would use
similar rules to "return" at the end of a method, allowing this to be
valid:

 var foo = do {
   if (a) {
     break "a";
   } else {
     break "b";
   }
};

As far as I can tell, there is no syntactic conflict with the existing
do...while statement, which would not be converted to an expression.
Alternately, it can be rationalised as being an invisible
while(false), as that form is the only one that is exhaustive.

An expression-switch would thus consist of only expressions as various
people have proposed. If you need a block, you use a block-expression.
Thus there is no fall-through, which is a fabulous result:

 var result = switch (foo) (
   case A -> "a"
   case B -> do {
     System.out.println("Found it");
     break "b";
   }
 };

> Combining with lambdas, we get 3 ways to do the same thing:
>
> x -> y
> x -> { return y; }
> x -> do { break y; }

While it could be argued that the fact it allows two ways to express
the same block-based lambda is a bad thing, I don't think its actually
a problem, the block form is rarely used anyway and the new form makes
lambdas more consistent. (Currently, a block lambda looks like a
method body, this changes that making it "just" an expression, which
is actually a nice shift in the mental model.

I think do...break block expressions would be a great addition to
Java. Especially as they take the bad parts away from e-switch, a good
win.

Stephen


More information about the amber-spec-observers mailing list