C# :Cyclomatic Complexity of a method with FxCop sdk

1.2k views Asked by At

I need to calculate the cyclomatic complexity of C# methods and need to define the rule according to the CC value, in the FXcop 12.0.

I've found that the tools like Code Metrics provide functionality to calculate the CC values, but I don't know how to use it in my code. Basically my requirement is the value of CC to reported via Sonar.

If anybody has written a custom rule for this or any idea how to do this, Please help

2

There are 2 answers

0
Dinesh Bolkensteyn On

In my opinion, it is not the exact absolute complexity value that matters, but the relative difference between your project and the average of all projects. Indeed, you can spot unusually high complex code this way.

If you really require the exact same complexity value report by FxCop to be available in SonarQube, then I would suggest that you write a SonarQube plugin to store that value as a metric, and rely on FxCop to compute it: Don't try to reverse-engineer how FxCop is computing it.

FYI, we have a long term plan to align the computation of metrics between SonarQube, Code Metrics, FxCop, etc. and use the same formulas, but this is will take time.

0
Patrick from NDepend team On

Maybe you can use the tool NDepend.

It is integrated with SonarQube.

It comes with both build-in code metrics:

It is integrated in Visual Studio and it makes it easy to write custom code rule. Such a rule is actually a C# LINQ query.

For example if you want to write a code rule to match methods that are both complex and poorly covered by tests, just write:

// <Name>Complex methods poorly covered by tests</Name>
warnif count > 0 
from m in Application.Methods
where m.CyclomaticComplexity > 10 && 
      m.PercentageCoverage < 20
select new { 
   m, 
   m.CyclomaticComplexity, 
   m.PercentageCoverage,
   m.NbLinesOfCode 
}

NDepend custom code rule cyclomatic complexity

Disclaimer: I work for NDepend