What is Cyclomatic Complexity ? And Why it matters ?
According to Wikipedia,
Cyclomatic complexity is a software metric (measurement), 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. It was developed by Thomas J. McCabe, Sr. in 1976.
How to compute it ?
There are 2 formulas, refer to cyclomatic complexity computation.
- M = E - N + 2P
- M = R + 1
here,
M = cyclomatic complexity,
E = number of edges in a graph
N = number of nodes in a graph
P = number of connected components (for simplicity, we can put P =1)
R = number of conditions in a program.
Example
/ A function to implement bubble sort
void bubbleSort(int arr[], int n)
{
int i = 0, j = 0;
while (i < n-1)
{
// Last i elements are already in place
while (j < n-i-1)
{
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
j++;
}
i++;
}
}
The flow chart is given below.
Here, P = 3, N = 9, E = 11, R = 3
So
M = 11 - 9 + 2(1) = 4
M = 3 + 1 = 4
Independents paths are given below.
- 1,2,3,4
- 1,2,3,4,8,3,9
- 1,2,3,4,5,6,7,8,3,9
- 1,2,3,4,5,7,8,3,9
Why it matters ?
Path testing is one of the White box testing technique and it guarantees to execute at-least one statement during testing. It checks each linearly independent path through the program, which means number of test cases will be equivalent to the cyclomatic complexity of the program.
Note: By using cyclomatic complexity, Although all paths are executed, all combinations of paths are not executed.
Dear Shaib, I found this article when I searched the internet to find resources related to the cyclomatic number of the bubble sort algorithm. I am afraid the code and the respective flowchart should reset the value of the variable j to zero after the completion of the inner loop. Please correct me if I am wrong. Thank you for sharing, Diab.