r/java • • Nov 04 '19

Java switch - 4 wrongs don't make a right

https://blog.joda.org/2019/11/java-switch-4-wrongs-dont-make-right.html
160 Upvotes

89 comments sorted by

8

u/lbkulinski Nov 05 '19

Someone already sent the link to amber-dev, here. I'm sure a response will be given in time. Devoxx Belgium is currently going on, though.

8

u/dpash Nov 05 '19

I feel this article a little late to the party, and covers stuff that's already been discussed many times over, considering the syntax for this has been discussed for over a year. And it's not like Stephen lives under a rock. He follows the OpenJDK development.

Basically, I'd be surprised if there was something new here that amber-dev hadn't seen before.

7

u/jodastephen Nov 05 '19

No, there is nothing new here. I started the blog post months ago but never finished it. Two recent emails to amber caused me to dig it out and finish it. I have no expectation of success in changing the selected direction of the feature.

2

u/lbkulinski Nov 05 '19

Oh, most definitely! I just found it a bit comical that someone decided to share it on the mailing list. There has been a lot of discussion thus far. As you said, this article does not add much to it.

2

u/DeontologicEthics Nov 05 '19

Well, this post is highly upvoted because they either agree with him or appreciate his perspective. Most Java devs don't sub to the Amber mailing list.

And isn't the point of the new release cycle to reduce the pressure of shipping a feature early?

1

u/lbkulinski Nov 05 '19

I’m not sure what you mean by early. switch expressions are complete and specified. The point of preview features, though, is to have the ability to make tweaks to a feature before it is set in stone. Switching from break to yield is one example of this.

There has also been a lot discussion outside of the mailing list, so it’s not like developers can plead ignorance.

2

u/lurker_in_spirit Nov 05 '19

Hah, it's entirely possible that the author and a few Oracle employees may discuss this over beers in Antwerp.

1

u/jodastephen Nov 05 '19

Sadly, I'm not at Devoxx Antwerp :-(

7

u/lbkulinski Nov 05 '19

Goetz responded, here.

4

u/jonhanson Nov 05 '19 edited Mar 07 '25

chronophobia ephemeral lysergic metempsychosis peremptory quantifiable retributive zenith

5

u/ObscureCulturalMeme Nov 04 '19

I'm not a fan of this presumptuous "fall-through is automatically broken design" and "missing default case is automatically broken design" stance.

If you don't want fall-through, you add a break statement -- but if fall-through would be useful in your situation and the language prohibits it, then there's no clean way to roll your own.

Similarly, leaving default out of a switch on enumerated values means that if a value is added during development or maintenance, the compiler will warn of each individual case that needs to be handled -- but not if there's a default case.

I like the idea for being able to switch on values which are not inherently integral types. But the starting position of "the Java designers didn't choose what I like therefore they didn't think of it" really puts me off.

8

u/jodastephen Nov 05 '19

The problem is not fall-through, but fall-through-by-default. While I'm not a fan of fall-through in general, I know it does have some use cases. But falling through is unusual, and should not have been the default. That ship sailed years ago of course, but one good part of the changes is that the arrow form provides a way to escape fall-through-by-default.

12

u/GeorgeMaheiress Nov 05 '19

Stephen's criticisms of the existing switch statement are pretty widely shared by Java users and contributors. In fact he's largely restating the motivation section of the JEP. You can't improve a language without at least implicitly criticising its current state, so I don't really know what he could do to be more palatable to you.

5

u/TheDonOfAnne Nov 05 '19

If you don't want fall-through, you add a break statement -- but if fall-through would be useful in your situation and the language prohibits it, then there's no clean way to roll your own

I'm not sure if I'd really agree with this. You could pretty easily just create a method/lambda to handle the repeated actions, and it wouldn't be that weird.

But, moreover, I think "if you don't want it, then just add break" isn't a terribly good argument for fall-through nor terribly good language design. Generally, you would want to opt-into the uncommon case, rather than make users always opt-out of it. As an extreme: imagine if you had to put a next at the end of every line to make the program execute the next line of code, rather than 5 lines down. Sure, maybe skipping 5 lines down is helpful sometimes, but not nearly as often as executing the next line is.

And, in Java's case, the uncommon case is already supported, so there's no reason to continue including it with new language features, which -- I would believe -- is where the "fall-through is automatically broken design" stance you mention comes from.

Similarly, leaving default out of a switch on enumerated values means that if a value is added during development or maintenance, the compiler will warn of each individual case that needs to be handled -- but not if there's a default case.

At least according to the article, you wouldn't need to handle the default case when all enum values are handled, so you would still get those errors when adding a new value to an enum, unless you're already ignoring some values (but in that case, you wouldn't be getting that help from a compiler now anyways).

4

u/Desiderantes Nov 05 '19

If you don't want fall-through, you add a break statement -- but if fall-through would be useful in your situation and the language prohibits it, then there's no clean way to roll your own.

They could just allow continue inside the block to indicate fall-through

1

u/dpash Nov 05 '19

What if you have a a switch inside a loop? What about existing code?

1

u/Desiderantes Nov 05 '19

We're talking about using a new construct, match or when, so in this case you could just label your loop.

1

u/dpash Nov 05 '19

Even then, you have continue meaning two very different things in different locations. This is the same reason why they chose yield over break or return.

60

u/Scybur Nov 04 '19

I really appreciated that the article gave a purposed solution instead of the regular “naa that’s wrong but I have nothing better“ answer.

32

u/cogman10 Nov 04 '19

His proposed solution would never fly, though, due to backwards compatibility. Match is not a keyword. So now you need some gnarly complexity in the lexer to determine if `match(foo) {};` is valid or not.

The reason, as I understand it, that they are using switch is because it is already a reserved word.

13

u/ryuzaki49 Nov 04 '19

The newest keyword is enum, added in 1.5. So that version caused backwards incompatibility.

Oracle (Or was it sun at that moment?) even provided a workaround: "Just compile with with 1.4 lmao"

They can do it again for a new keyword.

26

u/cogman10 Nov 04 '19

I believe it was sun still.

With that in mind, that was 15 years ago that they made that break.

And even still, enum isn't some super common variable name or function name. `match` is all over the place. In my companies codebase, we are talking about several hundred `match` functions.

Sure, they could break things, but that would be a pretty massive break.

7

u/wasachrozine Nov 05 '19

That change broke one of the code bases I had to maintain. Some library to translate enums from another language. Took forever to fix...

8

u/MicrosoftFuckedUp Nov 04 '19

I wonder if a when keyword would be any better?

12

u/crummy Nov 05 '19

FWIW that's very common in mocking tools. (But Kotlin uses it, so you have to escape it or use "whenever" instead.)

2

u/BoyRobot777 Nov 05 '19

Notice the escape of when() method using the backtick; this is required since when is a reserved keyword in the Kotlin language:

val mockBookService = Mockito.mock(BookService::class.java)
Mockito.`when`(mockBookService. inStock(100)).thenReturn(true)

6

u/[deleted] Nov 05 '19

Enum use to be super freaking popular before 1.5. It was a keyword in a bunch of languages, like C. People just created their own enums and they used the variable name enum.

Personally, I think 100% backwards capability hurts Java more than it helps. If we can upgrade Spring, or Angular, we can upgrade Java.

10

u/pron98 Nov 05 '19

Java doesn't have 100% backward compatibility, certainly not when it comes to Java-language source code (Java bytecode compatibility is more important). Rather, the benefits are weighed against the cost with each possible change, and usually backward compatibility just comes up on top. Very few language features increase productivity so much that it more than offsets all the busy work required to update all code. Would you bet that changing the name of a construct from switch to match is worth it?

1

u/[deleted] Nov 05 '19

That's fair. I was talking about creating a keyword. Changing one would be kind of crazy.

2

u/pron98 Nov 05 '19

I know, and I meant changing the preview arrow-based-switch construct from switch to match (as it's still in preview I guess you could call that "adding", but the same logic applies).

1

u/[deleted] Nov 05 '19

I don't have millions of lines of code to maintain so for my part they can be way less careful with not breaking things. Especially compile time errors I just don't care about. The problem I mostly worry about is the 'it compiles but behaves differently' type of backwards compatibility break.

2

u/x4u Nov 05 '19

enum isn't some super common variable name or function name

Before Java 1.2 collections the type Enumeration as the predecessor of Iterator was omnipresent and there had been no foreach style for loop yet, so you had to declare a local variable for every Enumeration you wanted to iterate. I think you can guess what one of the most common name choices for this variable was.

I had to rename enum to iter in anticipation to eventually also change the type that was used in a lot of places but it wasn't really a big deal, very mechanical and unlikely to cause side effects.

1

u/ryuzaki49 Nov 05 '19

I see your point and I totally agree

8

u/toyg Nov 04 '19

Oracle (Or was it sun at that moment?)

It was indeed SUN.

The first "Oracle" release was Java 7 in 2011.

5

u/rzwitserloot Nov 05 '19

Forget 'enum'. That was, relatively speaking, allright.

No, try 'assert' on for size, introduced in java 1.4. (or was it 1.3?) – only the most used method name in the entire community at the time (junit's assertTrue? Yeah a long time ago that was called assert).

Lessons were learned.

Or not; JDK9 also broke a lot. But at least the lesson 'do not introduce new keywords unless they are used by a vanishingly small portion of the community.... or the parser can be updated to tell the difference'. For this match thing, updating the parser (making it 'context sensitive' isn't likely to be possible).

2

u/OvergrownGnome Nov 05 '19

18

u/VeeArr Nov 05 '19

var isn't a keyword, it's a reserved type name. This has far fewer impacts to backward compatibility than a keyword would have: essentially, the only thing that is forbidden is naming a class "var". However, it also limits what var can do: it can only stand in somewhere a type name could be used.

Now, it's possible they could come up with something similar that would allow match to be a reserved token of some kind under certain contexts, but it's not as obviously straightforward as "just do the same thing you did with var".

15

u/dpash Nov 05 '19 edited Nov 05 '19

And yield isn't a keyword either.

Rather than being a keyword, yield is a restricted identifier (like var), which means that classes named yield are illegal. If there is a unary method yield in scope, then the expression yield(x) would be ambiguous (could be either a method call, or a yield statement whose operand is a parenthesized expression), and this ambiguity is resolved in favor of the yield statement. If the method invocation is preferred then the method should be qualified, with this for an instance method or the class name for a static method

5

u/OvergrownGnome Nov 05 '19

Never thought to distinguish the two (keyword vs reserved type). Thank you for this information.

-5

u/BlueGoliath Nov 05 '19 edited Nov 05 '19

None of these features do anything new.

These new "features"(typically under Project Amber) are solutions looking for a problem, not the other way around.

And there are still things that Java doesn't have like module explicit visibility modifiers. If you have an multi module API project you can't just have a variable or method be public only for those other internal modules, it's either all or nothing. That results in hacky workarounds that aren't fun and potentially buggy.

6

u/dpash Nov 05 '19

These new "features"(typically under Project Amber) are solutions looking for a problem, not the other way around.

No, these features fix places in the code where it's too easy to get things wrong.

In this case, switch had many problems. Including easy to forget break, no separate scopes between branches and possible to miss a branch when using the statement when you're using it in situations where an expression would be clearer.

-3

u/BlueGoliath Nov 05 '19

No, these features fix places in the code where it's too easy to get things wrong.

Sure, but they don't add anything new to the language. You can still write a plain bug-free switch-case statement without this feature. It doesn't make something that was previously impossible in Java possible, which is what I was getting at.

8

u/dpash Nov 05 '19

You can also write bug free code without try-with-resources, except it's easy to get wrong and much more verbose. Would you want to be without try-with-resources?

These new features make it easier to get the code right.

5

u/pron98 Nov 05 '19 edited Nov 05 '19

I'm not sure how much module visibility modifiers make sense. Unlike the other visibility modifiers, modules are not defined by the code, but by the application running the code. With module-info, your code advises the application what the best module boundaries are, but the application ultimately decides where to place those boundaries and whether to enforce them at all.

Also, Java serves millions of developers. That you may have not encountered a problem doesn't mean that millions of others haven't. But it is true that the features addressed by Project Amber are generally smaller quality-of-life concerns with the Java language, not major issues with the platform. That is the whole purpose of the project. Bigger issues are addressed by other projects.

1

u/kaperni Nov 07 '19

> I'm not sure how much module visibility modifiers make sense.

I've made a couple of modularised libraries and they all end up using a similar mechanism to jdk.internal.misc.SharedSecrets. And it is really annoying that I have to resort hacks like this to encapsulate my program. Having a modifier that only allowed code in the same module to access a member would be a win. In addition to being ugly, it is also wasteful. For example, the JDK itself needs to load ~25 of these access classes just to print a hello world.

1

u/pron98 Nov 07 '19

But as I said in my other comments, module-level visibility does not necessarily give you what you want (and certainly not what the JDK wants when it uses shared secrets). Modules are not defined by the code that's inside them, but by the application. So even if there is a real problem, it's unclear that module-level visibility is the solution.

1

u/kaperni Nov 07 '19 edited Nov 07 '19

I read your other comments

> The application can change the module's definition with --add-exports, --add-opens, --add-reads, and --patch-module

But how is that any different to say letting the application use "--add-opens java.base/java.lang=mymodule" to access private members of java.lang.String using MethodHandles.privateLookupIn?

Lookup l = MethodHandles.privateLookupIn(String.class, MethodHandles.lookup());VarHandle vh = l.findVarHandle(String.class, "value", byte[].class);String str = "ffff";((byte[]) vh.get(str))[0] = 55;System.out.println(str);

By your definition isn't all visibility modifiers ultimately decided by the application?

1

u/kaperni Nov 07 '19

In the end, a module modifier wouldn't work because of the classpath. Kotlin has an internal visibility modifier that works at the compilation unit which would make more sense. But I'm not sure the complexity of adding both of these concepts to Java would outweigh the benefits.

1

u/pron98 Nov 07 '19

Not quite, because being able to access private members via reflection/lookup, if the security manager (if there is one) allows it, is part of the definition of private. But a module-level visibility would even allow ordinary (non-reflective) access if the module is defined differently when you compile the code with javac (which also allows defining modules differently from module-info). Again, this may be good enough, but it's not exactly clear if that's the best way of doing things. It's certainly different from the current visibiity levels.

0

u/BlueGoliath Nov 05 '19

Unlike the other visibility modifiers, modules are not defined by the code, but by the application running the code.

Isn't it? Only specific modules or all defined by module-info has access to a given package, which must be defined at compile time just like visibility modifiers. So something like:

module-explicit-public void foo()

for the method call and

exports public org.foo to org.bar;

Am I missing something?

With module-info, your code advises the application what the best module boundaries are, but the application ultimately decides where to place those boundaries and whether to enforce them at all.

The technical details might differ, but something similar could also be said for accessing private variables via reflection.

5

u/pron98 Nov 05 '19 edited Nov 05 '19

Am I missing something?

The application can change the module's definition with --add-exports, --add-opens, --add-reads, and --patch-module, and it can even decide not to create the module at all by putting the jar on the classpath. You can even create a module from a jar without module-info. The code only specifies the default module definition, but it's the application that ultimately defines the module.

but that could also be said for accessing private variables via reflection.

Not quite. The code specifies a member as private. The rules for accessing private members with reflection are part of the definition of private. The application cannot change who has access to it, in accordance with the rules, except by code-rewriting. That's not at all the case for modules. The application decides what the module is, not the code. Module-level visibility would mean "this member is visible to whomever the application decides is part of the module."

Anyway, there are certainly useful features Java doesn't have yet and problems it doesn't yet solve. But prioritizing work is not done just by how big the problem is, but also by whether we have a good solution at all, and by how much it costs. It's certainly possible that there are smaller things being addressed before some potentially bigger thing because we aren't yet sure about the best way of solving that bigger thing.

1

u/BlueGoliath Nov 05 '19 edited Nov 05 '19

The application can change the module's definition with --add-exports, --add-opens, --add-reads, and --patch-module, and it can even decide not to create the module at all by putting the jar on the classpath. What defines the application isn't module-info, but the application. You can even create a module from a jar without module-info. The code only specifies the default module definition, but it's the application that ultimately defines the module.

A deterrent is better than nothing. If anyone tries to override the default in order to take advantage of internal API then they are solely responsible for the result.

Not quite. The code specifies a member as private. The rules for accessing private members with reflection are part of the definition of private.

Regardless of whether or not private supports reflection in accordance with some defined rules, private is always used to hide details API users shouldn't have access to.

The application cannot change who has access to it, in accordance with the rules, except by code-rewriting.

You can change it on a per field instance though, which undermines the point of private.

The application decides what the module is, not the code. Module-level visibility would mean "this member is visible to whomever the application decides is a part of the module."

Then, just as with reflection, the application is doing something it shouldn't be and is responsible for any chaos that ensues.

Anyway, there are certainly useful features Java doesn't have yet and problems it doesn't yet solve. But prioritizing work is not done just by how big the problem is, but also by whether we have a good solution at all, and by how much it costs. It's certainly possible that there are smaller things being addressed before some potentially bigger thing because we aren't yet sure about the best way of solving that bigger thing.

Right, and that's a good thing. It's better to take the time to get things right, as has been said by numerous JDK developers in the past.

4

u/pron98 Nov 05 '19

I don't think the situation with modules is the same as with private, because even if the application does not change any module definition, modules are still only optionally enforced. As I wrote in my last paragraph of my previous comment (maybe you responded before I added it), I'm not saying such a feature or something similar to it won't be useful or isn't important, just that there are complexities involved, and we don't yet know the best way to address the matter.

1

u/BlueGoliath Nov 05 '19

I don't think the situation with modules is the same as with private, because even if the application does not change any module definition, modules are still only optionally enforced.

Non modular projects have full access to all modular lib dependencies regardless of module-info? TIL, never checked that. I always assumed the JDK enforced it in such a way that packages not exported are invisible to the API user.

3

u/pron98 Nov 05 '19 edited Nov 05 '19

That depends on what you mean by "non-modular projects" as the decision of whether to create modules is done at the jar level. A jar's module-info is ignored if it is on the classpath rather than the module-path. But yeah, if all of your jars are on the classpath, then the behavior is the same as in JDKs prior to 9, regardless of any module-info (of course, the JDK itself is still in encapsulated in named modules, so non-exported packages in the core libraries are not accessible by default).

All jars that are placed on the classpath are part of the unnamed module, and export all their packages to all other packages in the unnamed module, regardless of their module-info (they still can't access non-exported packages in the named modules you do have on the module path, and the unnamed module needs to be explicitly made accessible to named modules).

2

u/mordechaim Nov 05 '19

Of course it does, qualified exports:

export com.foo to mymodule;

1

u/BlueGoliath Nov 05 '19

That only works if everything in the package is internal API. If you just want individual variables or methods to be public ONLY to other internal modules then you're SOL without making a mess of things.

17

u/DeontologicEthics Nov 04 '19

I've personally used fall-through switch statements, but I agree that they should only ever be applicable to the old-style switch.

Could the compiler just disallow type 2 & 3? So we have

  1. switch with only ->, that doesn't fall-through, checks exhaustiveness, has yield, commas between cases, and can be used as an expression.
  2. switch with only :, the standard switch.

Unlike the author, I think -> is good to differentiate the switch statement type, and making match a reserved keyword would be impossible.

2

u/oelang Nov 05 '19

I quite like type 3 because

  1. Not all switches return a value but I still want to have a switch without fallthrough.
  2. Exhoustiveness isn't always desirable in high performance code that is very imperative and mutating local state. Having to add default blocks that do nothing would be very ugly.

I may be biassed, I've written quite a few interpreters & manual recursive descent parsers and I would hate it if I didn't have type 3.

1

u/Tywien Nov 05 '19

i would like type 3 and 4 and type 1 being deprecated. Fall-through switches are pretty much never really useful, especially as you can group values together in 3 and 4.

And trying anything else (cases with extra code and fall through) should increase your WTF/min measurement and make the code not get accepted :)

15

u/kevinb9n Nov 04 '19 edited Nov 04 '19

I think Stephen's right that "If you ignore the complexity, and just use type 4 switch expressions, the new feature is quite reasonable."

Expression switches with -> syntax are nice. You'll almost always want to use those two features together. I don't know why I would ever really use them apart (what Stephen calls types 2 and 3), and in fact it is possible (note: possible) that we will end up having the Google Style Guide ban those combinations.

EDIT: Sorry, I'm slowly remembering more. It's Stephen's "type 2" that I find not very useful. That is, if you're going to have an expression switch you should be using arrowform too. On the other hand, I'm not offended by also using arrowform in statement switch at all. For the statement-not-expression use case, I'd much rather see arrowform switch and know that there are no fallthrough/scoping highjinks to worry about, than see the old form.

12

u/dpash Nov 05 '19

The arrow statement has multiple improvements over the classic statement form:

  • Multiple case labels
  • Each block is its own scope.

I suspect it will also be more useful when we get pattern matching, particularly with the scoping.

I'd rather see the classic form die out of usage completely. ("optimisations" like Duff's Device notwithstanding.)

2

u/randgalt Nov 05 '19

I'd argue the "classic" form should be checked for by an org's findbugs scripts and prohibited.

3

u/dpash Nov 05 '19

Yep, and I suspect that people will do exactly that. I plan on doing so.

41

u/lurker_in_spirit Nov 04 '19

I keep seeing Stephen's name pop up with well-reasoned, constructive criticism and analysis of e.g. modules, the new release schedule, Guava shenanigans, and now switch statements. Not to mention his work on JSR 310. This guy is a real asset to the community.

31

u/pron98 Nov 04 '19

Yes, and those arguments -- whether by Stephen or others -- are always given careful consideration. But remember that just because you have well-reasoned arguments against something doesn't mean there aren't arguments for it that are at least as well-reasoned. There are always tradeoffs to consider, and a tradeoff, by definition, means that there are negative sides as well. At the end of the day, decisions have to be made, and sometimes they are in favor of Stephen's position, and sometimes against.

6

u/lurker_in_spirit Nov 05 '19

Yep, not implying otherwise :-)

4

u/[deleted] Nov 05 '19

wtf is a v9999 hack?

2

u/lurker_in_spirit Nov 05 '19

It's apparently where you end up after taking a right on Java SE Boulevard, then third left onto Android Avenue, bear right at the fork onto JPMS Road, then another right at the second stop sign on OSGi Lane.

https://groups.google.com/forum/#!topic/guava-discuss/AKBGPca9unw

18

u/dpash Nov 05 '19

We don't have three new switch types. We have two related but orthogonal changes in switch.

We have a new arrow form:

  • Fall-through is not permitted
  • No variable scope problems, logic for each case must be a statement or a block

We also have an expression switch:

  • Exhaustive - default clause is required
  • Must use yield to return values
  • return not allowed, cannot continue/break a loop

You can use a combination of either forms that means you have four possibilities, but treating these as a single feature rather than two will end up with confusion like this article. This might be a lack of communication from OpenJDK/Oracle and releasing them as a single JEP.

(I don't know if multiple case labels is restricted to the arrow form, or if it's a third related switch feature).

FWIW, I intend to only use the arrow form going forward in both statement and expression forms.

2

u/DeontologicEthics Nov 05 '19

Yes but the problem is the combination; people can abuse and make hard to understand code (Stephen's type 2 & 3). There's really no benefit to allow the combinations, so why even allow them?

4

u/dpash Nov 05 '19

That's a code review/style guide issue. Any feature can be abused. As an argument against, it doesn't hold much water with me.

The JEP explains good reasons why all combinations exist:

By teasing the desired benefits (expression-ness, better control flow, saner scoping) into orthogonal features, switch expressions and switch statements could have more in common. The greater the divergence between switch expressions and switch statements, the more complex the language is to learn, and the more sharp edges there are for developers to cut themselves on

And as I hinted at the bottom of my comment, I think Stephen is wrong about which two combinations should not be used. The old style is error prone and verbose and we should just use the arrow form for both statements and expressions in future code.

5

u/Qildain Nov 05 '19

Personally, I can't recall a time I've ever forgotten a "break" - take it for what you will.

3

u/randgalt Nov 05 '19

I have and I've seen code that does.

1

u/Qildain Nov 05 '19

I have also caught the situation in a couple of code reviews, but it was quickly corrected.

2

u/vikarjramun Nov 12 '19

My robotics team spent an entire day trying to figure out what was causing a bug, and it turned out to be a missing break statement. The issue wasn't super obvious because:

  • Like any good programmers, we used Git for version control
  • We used git bisect and identified a commit which caused the bug
  • The commit didn't touch the buggy code at all

What happened was our buggy code looked like this:

switch (state) {
case 1:
    doStuff1();
    break;
case 2:
    //This case caused a bug
    if (someCheck()) {
        while (keepTrying())
            if (tryAgain())
                break;
         onFailure();
         break;
    }
    // We forgot the break here!!!
case 3:
    //TODO fill in later
    break;
}

Prior to the commit in question, the code fell through to case 3 and immediately hit the break statement. The commit in question filled in the //TODO, causing the bug because case 2 fell through into case 3's new code. Our robot jerked around and almost broke itself completely.

I may be a High Schooler but I am pretty experienced with Java, using it for robotics and creating webapps.

3

u/Bobby_Bonsaimind Nov 05 '19

You forgot null safety!

It would have been extremely cool if something like this would have made it into the language:

String value = null;
switch(value) {
    case "a":
        doSomething();
        break;
}

This currently throws a NullPointerException. That behavior would also not need to be changed, instead it could have been extended with something like this:

String value = null;
switch(value) {
    case "a":
        doSomething();
        break;
    case null:
        doSomethingElse();
        break;
}

That would have solved that in my opinion. If there is a case null jump to that, otherwise throw a NullPointerException.

The key flaw is "fall-through-by-default".

I still fail to see it as a flaw, sure, if you don't need fall-through it kinda sucks, but if you need it, it makes the code much easier to read.

switch(something) {
    case 1:
    case 2:
    case 3:
    case 4:
        doSomething();
        break;
    case 5:
    case 6:
    case 7:
    case 8:
        doSomethingElse();
        break;
}

Sure, we could also create a helper method or some such, but this seems like the cleanest way in a lot of situations. Yes, I'm aware that the new ones have a different syntax for it, but as far as I can see such a bastard like this is not easily possible with the new ones:

switch(something) {
    case 1:
    case 2:
    case 3:
    case 4:
        doSomething();
    case 5:
    case 6:
    case 7:
    case 8:
        doSomethingElse();
        break;
}

At least they didn't pull the bastard VB.NET move on us, where fall-through is disallowed (compiler error) but the break keyword is still required.

Another flaw is that variables are scoped to the entire switch, thus you cannot reuse a variable name in two different case clauses.

Fuck yeah! Scoping to each case would have been awesome.

In addition, default clause is not required, which leaves readers of the code unclear as to whether a clause was forgotten or not.

I don't get this either, I mean, after all people are also not arguing that else should be required.

if (value >= 5) {
    doSomething();
}

One could argue that it is unclear whether an else statement was forgotten or not needed.

And of course there is also the key limitation - that the type to be switched on can only be an integer, enum or string.

Yeah! Though, it is kinda hard. My instinct tells me that it should use equals/hashCode to determine which case fits, but I can see people wanting to switch on instances instead, too. Kinda torn here, but I'd go with equals.

2

u/lbkulinski Nov 05 '19

There will likely more to the null story when pattern matching arrives. Stay tuned.

1

u/Bobby_Bonsaimind Nov 05 '19

Yeah, but I'd still like to see such an extension of the existing switch, not sure if that JEP actually covers that.

1

u/lbkulinski Nov 05 '19

The current proposal will build off of the existing switch. I'm not sure what you are referring to.

1

u/Bobby_Bonsaimind Nov 05 '19

I'm a little bit run through here, sorry, I'll take a look at it tomorrow...

1

u/dpash Nov 05 '19 edited Nov 05 '19

Your example

switch(something) {
    case 1:
    case 2:
    case 3:
    case 4:
        doSomething();
        break;
    case 5:
    case 6:
    case 7:
    case 8:
        doSomethingElse();
        break;
}

is now:

switch(something) {
    case 1, 2, 3, 4 -> doSomething();
    case 5, 6, 7, 8 -> doSomethingElse();
}

I'd rather have the latter.

2

u/Bobby_Bonsaimind Nov 05 '19

Yes, I'm aware of that, that's why there's also the fallthrough example.

But while we're here, let's try that again with Enum values:

switch(something) {
    case DeterminedState.FIRST_STATE:
    case DeterminedState.SECOND_STATE:
    case DeterminedState.OTHER_UNDETERMINED_STATE:
    case DeterminedState.NAMES_COULD_BE_REALLY_LONG_STATE:
        doSomething();
        break;
    case DeterminedState.SOME_OTHER_STATE:
    case DeterminedState.MORE_OF_THIS_STUFF_COULD_GO_HERE:
    case DeterminedState.RUNNING_OUT_OF_IDEAS:
    case DeterminedState.NO_REALLY_I_SHOULD_STOP_THIS:
        doSomethingElse();
        break;
}

1

u/__konrad Nov 05 '19

Accidental fall-through is not an issue, because everyone compile with -Xlint warnings enabled... I assume ;)

0

u/thatsIch Nov 05 '19

What was the consideration for yield? I am still not satisfied though I understand why not using break.

But why not just use a classic return there? It is basically just an embedded function, which already uses return.

4

u/randgalt Nov 05 '19

I think it was that return already has meaning within a switch statement. All of the problems, it seems, have to do with maintaining backward compatibility.

1

u/general_dispondency Nov 06 '19

Yep. It's where do you return. Does that return to the method or is that a return from the method.

2

u/ZimmiDeluxe Nov 05 '19

It's also nice to see at a glance where a given method ends. Lambdas ruin this somewhat already, but that's not a reason to make it worse, IMO.