rewrite icon indicating copy to clipboard operation
rewrite copied to clipboard

"switch" statements should not contain non-case labels

Open aegershman opened this issue 4 years ago • 2 comments

see: https://rules.sonarsource.com/java/RSPEC-1219

Even if it is legal, mixing case and non-case labels in the body of a switch statement is very confusing and can even be the result of a typing error.

aegershman avatar Jul 21 '21 17:07 aegershman

It would be very difficult to write a recipe that fixes this without changing program semantics in potentially breaking ways. I don't think it is worth the effort to pursue.

sambsnyd avatar Aug 22 '21 22:08 sambsnyd

@sambsnyd A quick examination of how java treats this shows that this would not in fact be very hard:

@SuppressWarnings({"SwitchStatementWithTooFewBranches", "ConstantConditions", "UnusedLabel", "TextLabelInSwitchStatement"})
public class DanglingSwitchLabel {

    @Test
    void last() {
        int n = 0;
        switch (n) {
            // LABEL cannot appear here, won't compile
            case 0:
                // adding a break makes the label code unreachable and won't compile
                n++;
            LABEL:
                if(n == 1) {
                    n++;
                }
        }

        assertThat(n).isEqualTo(2);
    }
}

In effect, if the label isn't specifically jumped to by a continue or break comment, then the label can be removed and its contents folded into the break statement it implicitly belongs to.

jkschneider avatar Aug 23 '21 17:08 jkschneider