I recently (tonight) installed the Release Candidate for VS2005 (I believe it was the September CTP.) After an absolutely PAINLESS install process, I fired up the HA! code and started taking a look around VS2005. (I have been using the betas all along, but I was curious about some of the features I don’t normally use.
That’s when I stumbled across the “Run Code Analysis on…” menu option. So I ran it on HA! and came up with some interesting results. Not necessarily surprising, mind you, but interesting. The one that really caught my eye was an error that indicated I had a cyclomatic complexity of 120 on one of my routines. If you’re like me, you were probably wondering what that is exactly…
Cyclomatic complexity measures the number of linearly independent paths through the method, which is determined by the number and complexity of conditional branches. A low cyclomatic complexity generally indicates a method that is easy to understand, test, and maintain. The cyclomatic complexity is calculated from a control flow graph of the method and is given as
cyclomatic complexity = the number of edges – the number of nodes + 1
where a node represents a logic branch point and an edge represents a line between nodes.
The rule reports a violation when the cyclomatic complexity is greater than 25. (Oops! Mine was 120…)
It’s worth mentioning that depending on how you write code, there are ways to generate a “false positive” on this type of error. One example would be when using a large Select Case statement. (You C#’ers call them switches, I believe.) Fortunately, VS2005 gives you the means to exclude or suppress this notification.
In the case of my code, the offending routine had no logic branches at all… just a handful of For Next loops and a boatload of direct value assignments to various points in an array. (It was part of my map initialization routines.) Based on the above formula, the cyclomatic complexity should have been pretty low, certainly under 25. Oh well, nothing is perfect.