Cyclomatic Complexity

Cyclomatic complexity is one of the metrics in the area of Software Engineering, created by Thomas J.McCabe in 1976, that measures how complex a program is.

It’s a quantitative measurement and there can use different ways to measure it:

·       graph flow - https://en.wikipedia.org/wiki/Flow_graph_(mathematics)

·       Fluxogram

·       Statistic code analysis, using a tool to automate it (Sonar, for example)

Assuming that we’re using a graph flow or a fluxogram we have to use a formula similar to this:

M = E - N + 2P

where:

E = the number of the edges of the graph

N = the number of nodes of the graph

P = the number of connected components

Why you need to use it?

Cyclomatic complexity is an important indicator to measure the health of a project and to see how hard and how much time developers and testers are spending to solve a bug, to create new features, to test and to deploy without any issues. Humans have a limitation - we need to handle things with a cognitive load (used amount of working memory resources). If your code is complex and contains many layers and a lot of conditions to evaluate, the developer needs more time to concentrate and spend time making changes.

Tools

Luckily, no one needs to use that formula to calculate how complex a code is, we have tools that can handle it for us and show us our code complexity. To help with this, you can choose between:

·       Visual Studio - contains Code Metric built in IDE.

·       NDependend - https://www.ndepend.com/

·       Source Monitor - https://www.campwoodsw.com/sourcemonitor.html

·       SonarQube - https://www.sonarqube.org/

By using SonarQube, for example,  you can setup it in your Continuous Integration and avoid deploying a non-readable code.

Conclusion

When we are defining a system architecture it’s important that the architecture considers how complex it will be and there’s isn’t a magic tool to solve all the problems. As a developer it’s important to keep track if your code is not too complex to read and to make sure that it doesn’t have any over engineering.

References

·       https://www.ibm.com/docs/en/raa/6.1?topic=metrics-cyclomatic-complexity

·       https://en.wikipedia.org/wiki/Cyclomatic_complexity

·       https://en.wikipedia.org/wiki/Cognitive_load

Written by Lucas Rodrigues

Guest User