Note that there are some explanatory texts on larger screens.

plurals
  1. POSeeking clarifications about structuring code to reduce cyclomatic complexity
    text
    copied!<p>Recently our company has started measuring the cyclomatic complexity (CC) of the functions in our code on a weekly basis, and reporting which functions have improved or worsened. So we have started paying a lot more attention to the CC of functions.</p> <p>I've read that CC could be informally calculated as 1 + the number of decision points in a function (e.g. if statement, for loop, select etc), or also the number of paths through a function...</p> <p>I understand that the easiest way of reducing CC is to use the Extract Method refactoring repeatedly...</p> <p>There are somethings I am unsure about, e.g. what is the CC of the following code fragments?</p> <p>1)</p> <pre><code>for (int i = 0; i &lt; 3; i++) Console.WriteLine("Hello"); </code></pre> <p>And</p> <pre><code>Console.WriteLine("Hello"); Console.WriteLine("Hello"); Console.WriteLine("Hello"); </code></pre> <p>They both do the same thing, but does the first version have a higher CC because of the for statement?</p> <p>2)</p> <pre><code>if (condition1) if (condition2) if (condition 3) Console.WriteLine("wibble"); </code></pre> <p>And</p> <pre><code>if (condition1 &amp;&amp; condition2 &amp;&amp; condition3) Console.WriteLine("wibble"); </code></pre> <p>Assuming the language does short-circuit evaluation, such as C#, then these two code fragments have the same effect... but is the CC of the first fragment higher because it has 3 decision points/if statements?</p> <p>3)</p> <pre><code>if (condition1) { Console.WriteLine("one"); if (condition2) Console.WriteLine("one and two"); } </code></pre> <p>And</p> <pre><code>if (condition3) Console.WriteLine("fizz"); if (condition4) Console.WriteLine("buzz"); </code></pre> <p>These two code fragments do different things, but do they have the same CC? Or does the nested if statement in the first fragment have a higher CC? i.e. nested if statements are mentally more complex to understand, but is that reflected in the CC?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload