Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate cyclomatic complexity of a project (not a class/function)?

How to calculate cyclomatic complexity of the entire Java project? I have complexities for every method, but how to aggregate them all into one numeric metric? Any ideas or existing methods?

I'm not looking for a tool, but for an algorithm.

Simple average hardly works because there are many 1-complexity methods, which are not really of low complexity, but of low importance for the code base (in most cases).

like image 260
yegor256 Avatar asked Nov 26 '12 19:11

yegor256


1 Answers

Entire books have been written on code metrics, so you're lucky that you're asking a more specific question. For Java cyclomatic complexity, you could find the number of methods that exceed a cyclomatic complexity of 5 or 6 (you pick the number here). If this number exceeds more than a certain percentage of your number of methods, then the overall cyclomatic complexity is poor. A good number for the percentage depends entirely on the size of the project, so maybe instead of dividing only by the number of methods, you can put less weight on the method count in the division by making it grow slowly for large numbers, such as a square root or logarithm to try and make it more stable as the project grows.

Maybe something like this:

public double evaluateCyclomaticComplexity(List<MethodStat> methodStats) {
    int bad = 0;
    for (MethodStat methodStat : methodStats)
        if (methodStat.getCyclomaticComplexity() >= 6)
            bad++;

    double denominator = Math.sqrt(methodStats.size());
    return bad * 100.0 / denominator;
}

The smaller the number returned here, the better. For really bad project, this will return something greater than 100.

The denominator function should represent how fast you're okay with the complexity growing as the code base grows. Typically, you want the CC to be lower per function as the code grows so that it remains maintainable, so something that grows slower as the project size increases would be best.

Test it, tweak it, etc. Ultimately, code metrics are hard to get just right, which I can attest to after reading several journal papers on open source software that use numbers to represent "maintainability". Anything we can come up with here can likely be greatly improved if enough time is spent on it.

like image 191
Brian Avatar answered Nov 06 '22 04:11

Brian