Improve Code Maintenance with Visual Studio Code Metrics Analysis

There are several factors that make a code very difficult to maintain. Some of the most common factors are never ending functions that may have hundreds lines of code and functions that have deep nesting if then else statements. Visual Studio comes with a feature call Code Metrics. This is available in the Analyze menu options or by selecting the project you want to analyze and selecting the Calculate Code Metrics context menu option.
Maintainability Index
The main purpose of this utility is to calculate the maintainability index which provides a quick indicator of how difficult it may be to maintain the code. The goal is to get a high value with 100 being the maximum value. There may be an index of 50, but this does not mean the index is a poor one. Instead, there is a rating icon next to the index. This icon represents the category in which the code index falls on. These are the current color codes and ranges:

Green Rating
Code has good maintainability
Yellow Rating
Code is moderately maintainable
Red Rating
Code has poor maintainability

The goal is to achieve a green rating. I have noticed that code with rating below fifty could be easily refactored to improve the index. In your projects, you may want to target anything below 50 or 60.

Cyclomatic Complexity
This measures the number of different paths in the flow of the program. We need to remember that decision paths in a function require more test to get code coverage. A function with no decisions results in a value of one. A function with a value of eight or more should be refactored to improve the maintainability index.  Common problem areas that increase this value are the nesting of if then statements, comparison in a LINQ statement, switch statements.

Depth of Inheritance

This measures how deep classes are located in the inheritance tree. This can sometimes make it more difficult to understand in what parent class certain methods or properties are actually implemented. You should try to keep this value less than five

Class Coupling

This measures the use or coupling of other classes in a class method in the form of parameters, return types, method calls, attribute decoration. High coupling indicates that there is low maintainability because of the interdependencies on other classes that reside in the same assembly or on a different one. Anything over a value of eight should raise a flag, and the code should be reviewed.

Lines of Code

This is the most obvious indicator. Functions over 60 lines of code should be looked and split into more logical functions.

The recommended values I listed on this article should be used only as a suggestion for your projects. To get more accurate results, you should evaluate your projects and create a baseline that works for your goals. The key element here is to not let the code become something that is just too difficult and confusing to maintain.

I hope you find this useful.