Code Complexity
A quantitative measure of how difficult code is to understand, test, and maintain, based on factors like branching, nesting depth, and dependencies.
Definition
Code complexity is measured through various metrics: Cyclomatic Complexity (number of independent paths), Cognitive Complexity (Sonar's measure of understandability), Halstead metrics (based on operators and operands), and Lines of Code. High complexity correlates with higher defect rates and longer development times. Tools like SonarQube, ESLint (complexity rule), and diffray measure and flag complex code.
Why It Matters
Studies show that functions with cyclomatic complexity >10 are 4x more likely to have bugs. Complex code is hard to test (requires more test cases), review (easy to miss issues), and modify (high risk of regression). Keeping complexity low is a key quality metric.
Example
A function with 15 if/else branches, 4 nested loops, and 3 try/catch blocks has high complexity. Refactoring into smaller, focused functions with clear responsibilities reduces complexity and improves testability.