Measure Code Complexity Using Cyclomatic Complexity
Cyclomatic complexity is a measure of the decision structure complexity of code. The measure is used to quantify how difficult it is to understand or test a function or method.
The cyclomatic complexity value is the number of linearly independent paths and, therefore, the minimum number of paths that should be tested. The algorithm calculates an integer from 1 to infinity for any function, based on the number of possible paths through the function. Files with a complexity above 10 are candidates for simplification, and those above 50 are considered untestable.
The cyclomatic complexity value for any given piece of code starts at 1. Each
statement that creates a decision point (if
,
&&
, for
, and so on) increases the
value by 1. For example:
function cyclomaticTest(a) switch a case 1 disp("one") case 2 disp("two") case 3 disp("many") otherwise disp("lots") end end
You can measure the cyclomatic complexity of the function using checkcode
with the "-cyc"
option.
checkcode("cyclomaticTest.m","-cyc")
The McCabe cyclomatic complexity of 'cyclomaticTest' is 4.
This function has a cyclomatic complexity value of 4. The base value is 1, and 1 is
added for each case
statement. The switch
and
otherwise
statements do not increase the value. The cyclomatic
complexity reported by Code Analyzer for the MATLAB language is equivalent to the McCabe
cyclomatic complexity [1].
Modified cyclomatic complexity is a variation of cyclomatic complexity, where a
switch
statement increases the value by 1 regardless of how many
case
statements it contains. The reasoning is that
switch
statements are generally easier to understand than a
series of if
/elseif
statements. You can measure
the modified cyclomatic complexity using checkcode
with the
"-modcyc"
option.
checkcode("cyclomaticTest.m","-modcyc")
The modified cyclomatic complexity of 'cyclomaticTest' is 2.
This table lists the cyclomatic complexity values of various operations in MATLAB.
Operation | Cyclomatic Complexity Value | Modified Cyclomatic Complexity Value |
---|---|---|
Base complexity | 1 | 1 |
while | 1 | 1 |
for /parfor | 1 | 1 |
if /elseif | 1 | 1 |
else | 0 | 0 |
try | 1 | 1 |
catch | 0 | 0 |
&& operator | 1 | 1 |
|| operator | 1 | 1 |
switch | 0 | 1 |
case | 1 | 0 |
otherwise | 0 | 0 |
& operator | 1, only counted in while ,if ,
and elseif conditions. | 1, only counted in while ,if ,
and elseif conditions. |
| operator | 1, only counted in while ,if ,
and elseif conditions. | 1, only counted in while ,if ,
and elseif conditions. |
return | 0 | 0 |
break | 0 | 0 |
continue | 0 | 0 |
References
[1] Arthur H. Watson and Thomas J. McCabe, "Structured Testing: A Testing Methodology Using the Cyclomatic Complexity Metric." (National Institute of Standards and Technology, Gaithersburg, MD), NIST Special Publication (SP) 500-235 (September 1996). https://www.mccabe.com/pdf/mccabe-nist235r.pdf.