Non-case label in switch statement¶
ID: java/label-in-switchKind: problemSecurity severity: Severity: recommendationPrecision: very-highTags: - quality - maintainability - readabilityQuery suites: - java-code-quality.qls
Click to see the query in the CodeQL repository
Overview¶
Java allows to freely mixcase labels and ordinary statement labels in the body ofaswitch statement. However, this is confusing to read and may be the result of a typo.
Recommendation¶
Examine the non-case labels to see whether they were meant to becase labels. If not, consider placing the non-case label headed code into a function, and use a function call inline in theswitch body instead.
Example¶
publicclassTest{voidtest_noncase_label_in_switch(intp){switch(p){case1:// Compliantcase2:// Non-compliant, likely a typobreak;case3:notcaselabel:// Non-compliant, confusing to readfor(;;){breaknotcaselabel;}}}}
In the example,case2 is most likely a typo and should be fixed. For the intentionalnotcaselabel, placing the labelled code into a function and then calling that function is more readable.
References¶
CodeQL query help for JavaScript and TypeScript -Non-case label in switch statement.