Code Metrics for Visual Studio

Have you ever run Code Metrics in Visual Studio (2008)? When I first ran it, I got a plethora of numbers back for Cyclomatic Complexity, Class Couping, etc. I had no idea what most of these measures meant, so I’ve been going about finding out what each defines. The results have helped me find areas of code that need extra attention.

Maintainability Index

Is a summary measure of the other items in VS’s Code Metrics. The higher the number the better. I’ve read that you want to put some work into any code getting a score of 65 and lower to 80 and lower. Interestingly enough the worst “maintainability” components in my solutions are the auto-generated code for Windows Forms.

Cyclomatic Complexity

This measures how many “paths” your code contains. If you have a simple program with no conditions and no looping, you would have a CC of 1. The algorithm for determining complexity involves creating a node-based diagram and counting pathways and nodes. It can be also be determined by simply counting up each “if”, “else”, “for”, “while”, and “case” in a routine and adding 1. Generally for each member of a class you do not want complexity to exceed 10 or possibly 15. If you get extremely high complexity numbers you can see why you might want to check out that particular method, as it is probably not as easy to understand and maintain as other code.

Lowering the complexity of code involves refactoring. You may be doing several tasks in a single routine that you want to abstract out to another process. This would create another method in your code, but will allow for increased readibility and maintainability.

Depth of Inheritance

In .NET this is basically how many degrees the class lies away from it’s most basic ancestor class. For most classes this will be relative to System.Object. Interfaces can receive a DOI of 0.

Class Coupling

This is the number of classes the particular class in question is dependant on. The less dependency the less liable the code is to breaking.

Conclusion

There is also “lines of code” which is fairly self explanatory. In conclusion there is a healthy amount of criticism against code metrics – since it is an objective measure of code. However, if used with context in mind, I think these metrics can definitely help you find highly complex and unmaintainable chunks of code.

Advertisement

No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.