Skip to content

[java] MissingBreakInSwitch detects the lack of break in the last case #2579

@wuchiuwong

Description

@wuchiuwong

Affects PMD Version:
6.22.0

Rule:
MissingBreakInSwitch

Description:
MissingBreakInSwitch detects the lack of break in the last case, which is common and does not cause problems.
This rule is implemented through xpath search:

<![CDATA[
//SwitchStatement
[(count(.//BreakStatement)
 + count(BlockStatement//Statement/ReturnStatement)
 + count(BlockStatement//Statement/ContinueStatement)
 + count(BlockStatement//Statement/ThrowStatement)
 + count(BlockStatement//Statement/IfStatement[@Else='true' and Statement[2][ReturnStatement|ContinueStatement|ThrowStatement]]/Statement[1][ReturnStatement|ContinueStatement|ThrowStatement])
 + count(SwitchLabel[name(following-sibling::node()) = 'SwitchLabel'])
 + count(SwitchLabel[count(following-sibling::node()) = 0])
  < count (SwitchLabel))]
]]>

This rule detects whether a case is missing a break by comparing the number of cases in the switch and the number of statements exiting the case.
Therefore, when the last case lacks a break, it is also detected as an error.
It is recommended to adjust the detection way of the rule to reduce unimportant error warnings.

Code Sample demonstrating the issue:
Example 1:

switch (type) {
	case T_BYTES:
		intValue = byteC.getInt();
		break;
	default:
		intValue = Integer.parseInt(toString());
}

Example 2:

switch (paramInt) {
    case 0:
      this.a = paramDouble; break;
    case 1:
      this.b = paramDouble; break;
    case 2:
      this.c = paramDouble; break;
    case 3:
      this.d = paramDouble; break;
    case 4:
      this.e = paramDouble; break;
    case 5:
      this.tmin = paramDouble; break;
    case 6:
      this.tmax = paramDouble;
    }

Expected outcome:
false-positive

Running PMD through:
CLI

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:false-positivePMD flags a piece of code that is not problematic

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions