Saturday, May 10, 2008

Changing FxCop Maintainability and Cyclomatic Complexity rules

I'm finally moving to VSTS 2008, and yesterday I spent some time playing with the new Maintainability index. I am a big fan of NDepend and have used it for a year or so now in an effort to create more sustainable code, thus the new Maintainability index was promising to me. However, after finding out the range for the index is 0 - 100 and the thresholds are 10 for an error and 20 for a warning I was again disappointed with the extremely conservative implementation, just like I was with the high Cyclomatic Complexity thresholds.

How to change the thresholds
I started out trying to use the
same approach that worked with 2005 in order to change the FxCop thresholds for these two rules. However editing the IL and reconstituting the Maintainability.dll without the strong name doesn't work anymore with 2008 because it references two other strong named assemblies. Also, I was never really ethically satisfied with the old approach any way.

After looking at the assembly with
Reflector and reading a great tutorial on creating FxCop rules I started approaching the problem with the Decorator pattern to wrap the existing rules with my own. I assumed then that I could deactivate the Microsoft shipped version of the rules and activate my own in each Vs.Net project's Static Analysis settings. Implementing the Decorator pattern was a bit tricky though because the existing rules have both the Internal and Sealed modifier so I couldn't simply "new up" an instance nor could I inherit from the shipped types and override the pieces I wanted to augment. Luckily reflection provides a way to do everything that I needed even though the type signatures don't.

What I ended up with was a new JBBrown.FxCop.Rules.dll containing 3 class definitions - 1 abstract class and 2 new FxCop rules that implement the abstraction. The abstract class does the work of instantiating the Microsoft shipped rule, setting the thresholds and delegating FxCop API calls off to the decorated instance. The two new rules specify the new threshold values by providing the names of private variables within the Microsoft shipped rules to be reset to new custom chosen values. This is what the resulting VS.Net project's Static Analysis settings looks like when using the Decorated rules.






The Code
The entire source can be found here to allow you to set your own preferred thresholds for the Maintainability and Cyclomatic Complexity FxCop rules. After you compile the project then just drop the dll in your Rules directory and restart your Vs.Net. The FxCop rule directory path should be similar to "C:\Program Files\Microsoft Visual Studio 9.0\Team Tools\Static Analysis Tools\FxCop\Rules"

0 comments: