This checker aims to improve the readability of new-style arrow switches by simplifying and refactoring them.
case consists only of a yielding some value, it can be re-written with just the value. For example, case FOO -> { yield "bar"; } can be shortened to case FOO -> "bar";case FOO -> { System.out.println("bar"); } can shortened to case FOO -> System.out.println("bar");return switch:enum is covered by a case which returns, the return can be factored outenum SideOfCoin {OBVERSE, REVERSE}; private String renderName(SideOfCoin sideOfCoin) { switch(sideOfCoin) { case OBVERSE -> { return "Heads"; } case REVERSE -> { return "Tails"; } } // This should never happen, but removing this will cause a compile-time error throw new RuntimeException("Unknown side of coin"); }
The transformed code is simpler and elides the “should never happen” handler.
enum SideOfCoin {OBVERSE, REVERSE}; private String renderName(SideOfCoin sideOfCoin) { return switch(sideOfCoin) { case OBVERSE -> "Heads"; case REVERSE -> "Tails"; }; }
enum, if the cases are exhaustive, then a similar refactoring can be performed.switch:case just assigns a value to the same variable, the assignment can potentially be factored outswitch, the definition and assignment can potentially be combinedenum Suit {HEARTS, CLUBS, SPADES, DIAMONDS}; private void updateScore(Suit suit) { int score = 0; switch(suit) { case HEARTS, DIAMONDS -> { score = -1; } case SPADES -> { score = 2; } case CLUBS -> { score = 3; } } }
Which can be consolidated:
enum Suit {HEARTS, CLUBS, SPADES, DIAMONDS}; private void updateScore(Suit suit) { int score = switch(suit) { case HEARTS, DIAMONDS -> -1; case SPADES -> 2; case CLUBS -> 3; }; }