Skip to content

Commit

Permalink
Support switch statements correctly in Cognitive Complexity
Browse files Browse the repository at this point in the history
  • Loading branch information
gwilymatgearset committed Mar 2, 2020
1 parent 90f286a commit a32d12b
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import net.sourceforge.pmd.lang.apex.ast.ASTMethod;
import net.sourceforge.pmd.lang.apex.ast.ASTMethodCallExpression;
import net.sourceforge.pmd.lang.apex.ast.ASTPrefixExpression;
import net.sourceforge.pmd.lang.apex.ast.ASTSwitchStatement;
import net.sourceforge.pmd.lang.apex.ast.ASTTernaryExpression;
import net.sourceforge.pmd.lang.apex.ast.ASTWhileLoopStatement;
import net.sourceforge.pmd.lang.apex.ast.ApexNode;
Expand Down Expand Up @@ -231,4 +232,15 @@ public Object visit(ASTMethodCallExpression node, Object data) {
state.methodCall(node.getNode().getMethodName());
return super.visit(node, data);
}

@Override
public Object visit(ASTSwitchStatement node, Object data) {
State state = (State) data;

state.increaseNestingLevel();
super.visit(node, data);
state.decreaseNestingLevel();

return state;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -359,4 +359,35 @@
]]>
</code>
</test-code>

<test-code>
<description>Switch statements only gain 1 complexity regardless of the number of cases</description>
<expected-problems>1</expected-problems>
<expected-messages>
<message>'c__Foo#foo(Integer)' has value 3.</message>
</expected-messages>
<code>
<![CDATA[
class Foo {
void foo(Integer n) {
switch on n { // +1
when 1 {
System.debug('when block 1');
}
when 2, 3, 4, 5 {
if (n <= 3) { // +2
System.debug('n <= 3');
}
System.debug('when block 2');
}
when else {
System.debug('default');
}
}
}
}
]]>
</code>
</test-code>
</test-data>

0 comments on commit a32d12b

Please sign in to comment.