Search code examples
metricscyclomatic-complexity

Calculate Cyclomatic complex when it comes to a recursion function


Traditionally, Cyclomatic Complexity(CC) can be obtained by using the way that the number of "if-else" and then plus one. But when it comes to a recursion function, I found I unable to figure out the number of "if-else". More specifically, in this code block

public int m1(int k){
    if(k==0)
        return 0;
    else
        return m2(k-1)+(k%2);
}

public int m2(int k){
    if(k==0)
        return 0;
    else
        return m1(k-1)+(1-k%2);
}

How can I determine the CC of m1?

Explanation:

define a function CC(func) which stands for the CC of the function "func"

So, CC(m1) = 1(k==0) + CC(m2) (k!=0)

And CC(m2) = 1(k==0) + CC(m1) (k!=0)

I mean, we should take the CC of functions invoked into account.

Thanks for your help.


Solution

  • See https://en.m.wikipedia.org/wiki/Cyclomatic_complexity. Recursion by definition does not impact cyclomatic complexity and the tools measuring it also do not actually 'run' the code and measure it. This is because the original definition of McCabe states that CC is the number of possible path that the code can take, and that's about it. If you are still not convinced , just give it a different name, say recursive cylcomatic complexity, and measure it, by counting the actual number of invocations at runtime. Refer: https://www.guru99.com/cyclomatic-complexity.html