Home / Companies / Sourcegraph / Blog / Post Details
Content Deep Dive

Cyclomatic complexity: What it is and how to reduce it

Blog post from Sourcegraph

Post Details
Company
Date Published
Author
Matt Tanner
Word Count
3,301
Language
English
Hacker News Points
-
Summary

Cyclomatic complexity is a metric used to measure the number of independent paths through a block of code, which can indicate the maintainability and testability of the code. Developed by Thomas McCabe in 1976, it remains a critical tool for identifying potential defect risks and guiding refactoring efforts. The complexity score increases with each decision point, such as if statements or loops, making the code harder to test and maintain. While a score of 1-10 is considered low risk and manageable, higher scores suggest a need for refactoring. Essential complexity arises from inherent problem domain requirements, while accidental complexity stems from poor code structure, with the latter being the focus for refactoring. Teams can use tools like Code Insights and Code Search to identify complexity across entire codebases, ensuring that high-complexity functions are proactively managed rather than discovered incidentally. Cyclomatic complexity is complemented by cognitive complexity, which accounts for human understanding and readability, providing a more comprehensive view of code quality.