Cyclomatic Complexity | Examples and Tools


Cyclomatic Complexity

Cyclomatic complexity is a software metric used to measure the complexity of a program. These metric measures independent paths through program source code.

  • Independent path is defined as a path that has at least one edge which has not been traversed before in any other paths.
  • Cyclomatic complexity can be calculated with respect to functions, modules, methods or classes within a program.
  • it is based on a control flow representation of the program.
  • Control flow depicts a program as a graph which consists of Nodes and Edges.
  • It is calculated by developing a Control Flow Graph of the code that measures the number of linearly-independent paths through a program module.
  • Lower the Program’s cyclomatic complexity, lower the risk to modify and easier to understand.

It can be represented using the below formula:

Cyclomatic complexity = E – N + 2*P

  where,

  E = number of edges in the flow graph

  N = number of nodes in the flow graph

  P = number of nodes that have exit points

 


Example

IF A = 10 THEN
 IF B > C THEN
   A = B
 ELSE
 A = C
 ENDIF
ENDIF
Print A
Print B
Print C

Flow GraphCyclomatic Complexity

The Cyclomatic-complexity is calculated using the above control flow diagram that shows seven nodes (shapes) and eight edges (lines).

Hence, the cyclomatic complexity is 8 – 7 + 2 = 3

Tools for Cyclomatic Complexity calculation

Many tools are available for determining the complexity of the application. Some complexity calculation tools are used for specific technologies. Complexity can be found by the number of decision points in a program.

Examples of tools are

  • OCLint : Static code analyzer for C and Related Languages
  • devMetrics : Analyzing metrics for C# projects
  • Reflector Add In : Code metrics for .NET assemblies
  • GMetrics : Find metrics in Java related applications
  • NDepends : Metrics in Java applications

Uses of Cyclomatic Complexity

The uses of the Cyclomatic-Complexity can be summarized under the following points:

  • Helps developers and testers to determine independent path executions.
  • Developers can assure that all the paths have been tested at least once.
  • Helps us to focus more on the uncovered paths.
  • Improve code coverage.
  • Evaluate the risk associated with the application or program.
  • Using these metrics early in the cycle reduces more risk of the program.

 

260 total views, 1 views today

A Soon-to-be Computer Engineer by profession, he has profound devotion to add Data Scientist as a prefix to his name. He’s been to the nooks of the web (at least of the surface web) and planning to add some real figures in his pocket!

Leave a Reply