Increase cognitive complexity on recursion

This commit is contained in:
Gwilym Kuiper
2020-02-18 17:06:18 +00:00
parent 0231350dea
commit 9d0fb82d6f
2 changed files with 47 additions and 0 deletions

View File

@ -11,7 +11,9 @@ public class CognitiveComplexityVisitor extends ApexParserVisitorAdapter {
public static class State {
private int complexity = 0;
private int nestingLevel = 0;
private BooleanOp currentBooleanOperation = null;
private String methodName = null;
public double getComplexity() {
return complexity;
@ -44,6 +46,16 @@ public class CognitiveComplexityVisitor extends ApexParserVisitorAdapter {
void decreaseNestingLevel() {
nestingLevel--;
}
void methodCall(String methodCalledName) {
if (methodCalledName.equals(methodName)) {
structureComplexity();
}
}
void setMethodName(String name) {
methodName = name;
}
}
@Override
@ -185,4 +197,18 @@ public class CognitiveComplexityVisitor extends ApexParserVisitorAdapter {
return data;
}
@Override
public Object visit(ASTMethod node, Object data) {
State state = (State) data;
state.setMethodName(node.getNode().getMethodInfo().getCanonicalName());
return super.visit(node, data);
}
@Override
public Object visit(ASTMethodCallExpression node, Object data) {
State state = (State) data;
state.methodCall(node.getNode().getMethodName());
return super.visit(node, data);
}
}

View File

@ -338,4 +338,25 @@
]]>
</code>
</test-code>
<test-code>
<description>Recursion bumps complexity value</description>
<expected-problems>1</expected-problems>
<expected-messages>
<message>'c__Foo#foo(Integer)' has value 3.</message>
</expected-messages>
<code>
<![CDATA[
class Foo {
Integer foo(Integer n) {
if (n == 0 || n == 1) { // +2
return 1;
}
return n * foo(n - 1); // +1
}
}
]]>
</code>
</test-code>
</test-data>