Cyclomatic definition: Used to describe the number of circuits in a network; equal to the number of edges minus the number of nodes plus the number of graphs.
Ok, breathe. If we translate the definitions into code, it will be something like this.
Nodes are like the conditional statement: if
, else
, while
, for
, etc.
Edges are the paths that can be taken. There are two paths in the code on lines 4
and 14
. One of the two can be taken if the variable defined on line 3
has the value of Hola
; in this case, the first path will be taken. But in this example, the value of the $a
is Helloworld
so the second path will be taken. In the control flow graph below, you can view a better representation.
Ok, right; what is the complexity of that cool name I previously told you about?
The code above is a small example, but imagine you have a method that has 100 lines of code. Then, the complexity of the code will increase drastically.
The equation for calculating the cyclomatic complexity is:
$M = N - E + 2P$
This formula is also known as McCabe’s Cyclomatic Complexity (MCC) and is widely used to measure the complexity of a program by analyzing its control flow structure.
N
stands for the number of nodes, and E
stands for the number of edges. The 2P
stands for two multiplied by the number of exit nodes. In our example, this will translate into:
$5 = 8 - 9 + 2 x 3$
<?php
namespace Test\e9;
class Complex {
public function getChapter(int $number, Charachter $Charachter): bool {
if (1 === 1) {
switch (1) {
case 2:
if (true) {
if (false) {
}
};
}
if (2 === 2) {
if (3 === 3) {
if (4 === 4) {
if (5 === 5) {
if (6 === 6) {
return true;
}
}
}
}
}
}
}
}