Cyclomatic complexity: When to refactor your code?
Everyone in the software industry wants to refactor their code yet very few are willing to do it.
New feature requests keep coming and we are adding new code to the code base. The code base grows exponentially. The more cup of coffee we intake, the more lines of code we are adding.
After a certain period of time, It gets harder to debug or fix a bug or make changes. No one wants to take responsibility to help the newcomer to understand the code base.
It is the time we ask ourselves a few questions —
- Is the program/functionality testable?
- Is the program/functionality understood by everyone?
- Is the program/functionality reliable enough?
We can answer the questions above using cyclomatic complexity. Cyclomatic complexity is used to determine the complexity of a piece of code. It is also a way to determine if your code needs to be refactored. Complexity is determined by branching (if statements, etc.). it can be represented by the following 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
Source: Tutorialspoint
The control flow shows seven nodes (shapes) and eight edges (lines). So using the formal formula the cyclomatic complexity is 8–7 + 2 = 3
Note that: for a single program (or subroutine or method), P is always equal to 1.
Well, That was the hard way to calculate cyclomatic complexity. The easiest way to calculate the cyclomatic complexity using the decision points rule. Since there are two decision points, the cyclomatic complexity is 2 + 1 = 3
Basic rules to determine if your methods need to be refactored:
- < 10 Easily maintainable
- 11–20 Harder to maintain
- 21+ Need to refactor or Rewrite
Also keep in mind that, higher complexities make the code harder to unit test