Cyclomatic Complexity - arnthor89/pygame GitHub Wiki

Cyclomatic complexity (CC)

Cyclomatic complexity is a software metric used to indicate the complexity of a program. It is a quantitative measure of the number of linearly independent paths through a program's source code.

How to calculate it by hand

Cyclomatic complexity is computed using the control flow graph of the program: the nodes of the graph correspond to indivisible groups of commands of a program, and a directed edge connects two nodes if the second command might be executed immediately after the first command. M = E − N + 2P, where E is the number of edges, N is the number of nodes, P is the number connected components.

Example

if( c1() )
   f1();
else
   f2();

if( c2() )
   f3();
else
   f4();

Control flow representation (ignore the edge connecting the blue and red nodes):
The resulting CC is: 8 - 7 + 2*1 = 3 (8 edges, 7 nodes, 1 connected components).

Implication for software testing

Another application of cyclomatic complexity is in determining the number of test cases that are necessary to achieve thorough test coverage of a particular module. Intersting result: branch coverage ≤ cyclomatic complexity ≤ number of paths. This means that if you designed a number of different test cases equal to the CC you'd achieve for sure the branch coverage.

Limiting the complexity of subroutine

One of the original applications of CC was to limit the complexity of routines during program development; the founder McCabe of the method recommended that programmers should count the complexity of the modules they are developing, and split them into smaller modules whenever the cyclomatic complexity of the module exceeded 10. This practice was adopted by the NIST Structured Testing methodology, with an observation that since McCabe's original publication, the figure of 10 had received substantial corroborating evidence, but that in some circumstances it may be appropriate to relax the restriction and permit modules with a complexity as high as 15.
For this project it's reasonable to set our threshold for CCN to 10.

Reference: Wikipedia