Improving Code Quality - Code Metrics

Code metrics can give you a good picture really quickly of what “condition” your codebase is in. To run code metrics, go to Analyze > Calculate Code Metrics > For Solution. This may take a little while depending on how big your project is.

Once the Code Metrics have been calculated, you can view the results in the Code Metrics Results Pane:

So what have we got going on here? The first column – maintainability. This tells you how maintainable your code is based on the factors that Code Metrics analyses. This gives you a colour result as well – in my case all green (phew!).


The next is cyclomatic complexity. This is a measure of how complex your code is. For example, a method with a foreach loop containing an if statement containing a switch statement containing a while loop will have a high cyclomatic complexity. Where possible, relook at the logic if you have any high cyclomatic complexity. It is worth noting at this point that you can drill down in the Code Metrics Results pane using the arrows to the left of each project to see where your highest numbers are coming from.

Where did you come from?

The next column is depth of inheritance. I was surprised that I had a depth of 4 with my project, however this does include classes inherited in the provided libraries, so for example I have an AccountController (my class) inheriting from a BaseController (my class) inheriting from a Controller (Microsoft’s class) inheriting from a ControllerBase (Microsoft’s class). So 4 doesn’t really seem that bad in this context.

We're a team...

Class coupling is a rating of how dependent your classes are on other classes. I found my highest ratings for this were my image manipulation classes, due to their dependencies on many other classes from the GDI library – such as Bitmap, Image, Graphics, Memory Stream etc.

Close your eyes and count to 100..

Finally lines of code. This doesn’t really tell you much – obviously the higher the lines of code, the bigger the project – it may be you can use this metric to decide when to split functionality out into separate projects to improve maintainability.

Next: Improving Code Quality - Code Clones

Tagged: Code Quality, Visual Studio, .Net,
Categorised: Application Lifecycle Management,