Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtaining Cyclomatic Complexity

I am looking into calculating the cyclomatic complexity of java methods using Rascal.

One approach to this would be:

  • getting the AST from the method
  • use visit pattern on this tree
  • check for the following keywords which all increase the CC with one: case, catch, do, while, if, for, foreach

Another one is using graph theory and using the formula e-n+2. both e and n can be obtained quite easily using rascal functionality. My problem is how do I go about constructing the control flow graph, I found the following module: analysis::flow::ControlFlow which seems to be a step in the right direction but I am totally lost on where to go from there.

like image 327
Lorenzo.A Avatar asked Jan 06 '23 05:01

Lorenzo.A


1 Answers

The easiest way is indeed counting the forking nodes on the AST.

In our publication that explained SLOC and CC do not have a strong correlation to each other (preprint), we have also shared our rascal code to calculate CC (see Figure 2).

Here is the code extracted from the article, first create the file's AST with m3, and search for all methods/code blocks in the file. Per method you call this rascal function that visits the AST and counts certain nodes.

int calcCC(Statement impl) {
    int result = 1;
    visit (impl) {
        case \if(_,_) : result += 1;
        case \if(_,_,_) : result += 1;
        case \case(_) : result += 1;
        case \do(_,_) : result += 1;
        case \while(_,_) : result += 1;
        case \for(_,_,_) : result += 1;
        case \for(_,_,_,_) : result += 1;
        case \foreach(_,_,_) : result += 1;
        case \catch(_,_): result += 1;
        case \conditional(_,_,_): result += 1;
        case \infix(_,"&&",_) : result += 1;
        case \infix(_,"||",_) : result += 1;
    }
    return result;
}
like image 182
Davy Landman Avatar answered Feb 11 '23 05:02

Davy Landman