Unused label¶
ID: java/unused-labelKind: problemSecurity severity: Severity: recommendationPrecision: highTags: - quality - maintainability - useless-code - external/cwe/cwe-561Query suites: - java-security-and-quality.qls
Click to see the query in the CodeQL repository
Loop andswitch statements can be labeled. These labels can serve as targets forbreak orcontinue statements, to specify which loop orswitch statement they refer to.
Apart from serving as such jump targets, the labels have no effect on program behavior, which means that having an unused label is suspicious.
Recommendation¶
If the label is used to document the intended behavior of a loop orswitch statement, remove it. It is better to use comments for this purpose. However, an unused label may indicate that something is wrong: that some of the nestedbreak orcontinue statements should be using the label. In this case, the current control flow is probably wrong, and you should adjust some jumps to use the label after checking the desired behavior.
Example¶
The following example uses a loop and a nested loop to check whether any of the currently active shopping carts contains a particular item. On line 4, thecarts: label is unused. Inspecting the code, we can see that thebreak statement on line 10 is inefficient because it only breaks out of the nested loop. It could in fact break out of the outer loop, which should improve performance in common cases. By changing the statement on line 10 to readbreakcarts;, the label is no longer unused and we improve the code.
publicclassWebStore{publicbooleanitemIsBeingBought(Itemitem){booleanfound=false;carts:// AVOID: Unused labelfor(inti=0;i<carts.size();i++){Cartcart=carts.get(i);for(intj=0;j<cart.numItems();j++){if(item.equals(cart.getItem(j))){found=true;break;}}}returnfound;}}
References¶
Help - Eclipse Platform:Java Compiler Errors/Warnings Preferences.
Common Weakness Enumeration:CWE-561.