Вопрос

I found this site claiming that Cyclomatic Complexity = ( 2 + ifs + loops +cases - return ) and I also found out that Cyclomatic Complexity can be calculate by the number of conditional statement + 1 which is basically the same.

Now the above states that for each case in a switch add +1 to Cyclomatic Complexity, what happens if I have a return statement in each case?

For example would the CC of the below code still be 4 or 2?

function(someVal) {
switch (someVal) {
    case 1: return something;
    case 2: return something;
    case 3: return something;
        doSomething();
        break;
    default:
        doSomethingElse();
        break;
}

}

Это было полезно?

Решение

Cyclomatic complexity is the number of linearly independent paths through a program. In other words how many distinct paths are there from the entry point to the exit point. This in turn is an indicator as to how complex the underlying program is and gives a lower bound for the number of test cases you would need to get full path coverage of the module (here full path coverage means executing every line of code at least once).

There are several approaches to calculating the number of paths through a program, most based on graph theory. Many of these have been summarized into simple counting rules such as the one you are using.

Now to answer your specific question. What is the cyclomatic complexity of your program? Consider the program structure chart:

enter image description here

How many paths are there through this chart? Using the edge numbers we have the following paths:

  1, 2
  1, 3, 4
  1, 3, 5, 6, 7
  1, 3, 5, 8, 9

There are 4 linearly independent paths through this program. Cyclomatic complexity is 4.

There are other ways to come up with the same result assuming a structured program (no crossing lines in the structure chart):

 edges - nodes + 2 = 9 - 7 + 2 = 4
 Number of enclosed spaces in the structure chart plus 1 (3 + 1 = 4)

The original definition of Cyclomatic complexity is: v(G) = E - N + 2P. Where E = Edges, N = Nodes and P = number of modules (graphs). Since we genearlly apply Cyclomatic complexity to single modules, P is almost always 1.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top