Merge branch 'pr-2321'

[apex] Support switch statements correctly in Cognitive Complexity
This commit is contained in:
Andreas Dangel
2020-03-02 20:28:46 +01:00
3 changed files with 44 additions and 0 deletions

View File

@@ -180,6 +180,7 @@ methods on {% jdoc apex::lang.apex.ast.ApexParserVisitor %} and its implementati
* [#2280](https://github.com/pmd/pmd/pull/2280): \[cs] CPD: Replace C# tokenizer by an Antlr-based one - [Maikel Steneker](https://github.com/maikelsteneker)
* [#2297](https://github.com/pmd/pmd/pull/2297): \[apex] Cognitive complexity metrics - [Gwilym Kuiper](https://github.com/gwilymatgearset)
* [#2317](https://github.com/pmd/pmd/pull/2317): \[apex] New Rule - Test Methods Must Be In Test Classes - [Brian Nørremark](https://github.com/noerremark)
* [#2321](https://github.com/pmd/pmd/pull/2321): \[apex] Support switch statements correctly in Cognitive Complexity - [Gwilym Kuiper](https://github.com/gwilymatgearset)
{% endtocmaker %}

View File

@@ -16,6 +16,7 @@ import net.sourceforge.pmd.lang.apex.ast.ASTIfElseBlockStatement;
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;
@@ -231,4 +232,15 @@ public class CognitiveComplexityVisitor extends ApexParserVisitorAdapter {
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;
}
}

View File

@@ -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>