Skip to content

Commit 392d12a

Browse files
committed
Cyclomatic complexity computation for analysis level 1
Signed-off-by: Saurabh Sinha <[email protected]>
1 parent 1ad2b92 commit 392d12a

File tree

1 file changed

+23
-1
lines changed

1 file changed

+23
-1
lines changed

src/main/java/com/ibm/cldk/SymbolTable.java

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
import com.github.javaparser.ast.body.*;
1111
import com.github.javaparser.ast.expr.*;
1212
import com.github.javaparser.ast.nodeTypes.NodeWithName;
13-
import com.github.javaparser.ast.stmt.BlockStmt;
13+
import com.github.javaparser.ast.stmt.*;
1414
import com.github.javaparser.ast.type.ReferenceType;
1515
import com.github.javaparser.ast.type.Type;
1616
import com.github.javaparser.resolution.declarations.ResolvedMethodDeclaration;
@@ -301,11 +301,33 @@ private static Pair<String, Callable> processCallableDeclaration(CallableDeclara
301301
callableNode.setAccessedFields(getAccessedFields(body, classFields, typeName));
302302
callableNode.setCallSites(getCallSites(body));
303303
callableNode.setVariableDeclarations(getVariableDeclarations(body));
304+
callableNode.setCyclomaticComplexity(getCyclomaticComplexity(callableDecl));
304305

305306
String callableSignature = (callableDecl instanceof MethodDeclaration) ? callableDecl.getSignature().asString() : callableDecl.getSignature().asString().replace(callableDecl.getSignature().getName(), "<init>");
306307
return Pair.of(callableSignature, callableNode);
307308
}
308309

310+
/**
311+
* Computes cyclomatic complexity for the given callable.
312+
*
313+
* @param callableDeclaration Callable to compute cyclomatic complexity for
314+
* @return cyclomatic complexity
315+
*/
316+
private static int getCyclomaticComplexity(CallableDeclaration callableDeclaration) {
317+
int ifStmtCount = callableDeclaration.findAll(IfStmt.class).size();
318+
int loopStmtCount = callableDeclaration.findAll(DoStmt.class).size() +
319+
callableDeclaration.findAll(ForStmt.class).size() +
320+
callableDeclaration.findAll(ForEachStmt.class).size() +
321+
callableDeclaration.findAll(WhileStmt.class).size();
322+
int switchCaseCount = callableDeclaration.findAll(SwitchStmt.class).stream()
323+
.map(stmt -> stmt.getEntries().size())
324+
.reduce(0, Integer::sum);
325+
int conditionalExprCount = callableDeclaration.findAll(ConditionalExpr.class).size();
326+
int catchClauseCount = callableDeclaration.findAll(CatchClause.class).size();
327+
int cyclomaticComplexity = ifStmtCount + loopStmtCount + switchCaseCount + conditionalExprCount + catchClauseCount + 1;
328+
return cyclomaticComplexity;
329+
}
330+
309331
/**
310332
* Processes the given field declaration to extract information about the
311333
* declared field and

0 commit comments

Comments
 (0)