Cyclomatic Complexity
A software metric that measures the number of independent paths through a program's source code, indicating code complexity and testability.
التعريف
Developed by Thomas McCabe in 1976, cyclomatic complexity counts the number of linearly independent paths through code. It's calculated as: M = E - N + 2P (edges minus nodes plus 2 times connected components). Each if, while, for, case, catch, &&, ||, and ternary operator increases complexity by 1. Generally: 1-10 is simple, 11-20 is moderate, 21-50 is complex, 50+ is untestable.
لماذا هو مهم
High cyclomatic complexity indicates code that's hard to test, understand, and maintain. Studies show that functions with complexity over 10 have significantly higher defect rates. Static analysis tools flag high complexity as a code smell requiring refactoring.
مثال
A function with 3 if statements and a loop has cyclomatic complexity of 5 (1 base + 3 ifs + 1 loop). This means there are 5 distinct paths through the code, each requiring a test case for full coverage.