[java] SwitchDensity: Fix FP with default label

This commit is contained in:
Andreas Dangel committed 2021-08-22 21:40:52 +02:00
1 parent 2df54339e7
commit ea79544a59
2 files changed
+26 -1

No files matched your search

@@ -7,6 +7,7 @@ package net.sourceforge.pmd.lang.java.rule.design;
import static net.sourceforge.pmd.properties.constraints.NumericConstraints.positive;
import net.sourceforge.pmd.lang.java.ast.ASTStatement;
import net.sourceforge.pmd.lang.java.ast.ASTSwitchBranch;
import net.sourceforge.pmd.lang.java.ast.ASTSwitchExpression;
import net.sourceforge.pmd.lang.java.ast.ASTSwitchLike;
import net.sourceforge.pmd.lang.java.ast.ASTSwitchStatement;
@@ -53,7 +54,9 @@ public class SwitchDensityRule extends AbstractJavaRulechainRule {
public Void visitSwitchLike(ASTSwitchLike node, Object data) {
// note: this does not cross find boundaries.
int stmtCount = node.descendants(ASTStatement.class).count();
int labelCount = node.getBranches().sumBy(branch -> branch.getLabel().getExprList().count());
int labelCount = node.getBranches()
.map(ASTSwitchBranch::getLabel)
.sumBy(label -> label.isDefault() ? 1 : label.getExprList().count());
// note: if labelCount is zero, double division will produce NaN, not ArithmeticException
double density = stmtCount / (double) labelCount;
@@ -113,6 +113,28 @@ public class SwitchDensity3 {
}
}
}
}
]]></code>
</test-code>
<test-code>
<description>False positive with default label</description>
<rule-property name="minimum">10</rule-property>
<expected-problems>0</expected-problems>
<code><![CDATA[
public class SwitchWithDefault
{
public void someMethod()
{
int i = 0;
switch (i)
{
default:
i--;
i++;
break;
}
}
}
]]></code>
</test-code>