Measure Your Code Using Code Metrics

Overview

As a developer, when you are developing applications, how optimistic are you about delivering quality code? Quality code means not only bug free code but also understandable, maintainable, extensible, less complex and loosely coupled code. 

  • How can I measure my code?
  • How can I believe my code is perfect and good quality code?
  • What are the possible ways to recognize the code smells in my code base?

For all those queries, we have one solution is ‘CODE METRICS’. Code metrics has really helped me over the years and given me the confidence about my code and improvements in my code as well as inspecting other team members' code.

Advantages of Code Metrics Tool

  1. Identify the code smells
    It means identify the design flaws or bad practices, which might require attention, either immediately or at a later point of time. Some of the common code smells are Long Method, Duplicate Code, Large Class, and Dead Code.
  1. Identify the complexity and maintainability of your code
    It’ll give you an insight of your code maintainability and complexity.
  1. Increase your Code Review efficiency.

Code Metrics Measurements

“Code Metrics is a tool which analyzes our project, measures the complexity and provides us better insight into the code.”

To generate code metrics for our project, we can go to Analyze Menu –> Calculate Code Metrics.

CODE METRICS

The following list shows the code metrics results that Visual Studio calculates,

Maintainability Index

It indicates how easy it should be to understand and modify the code. The maintainability index metric can be used as an overall quality indicator and this index will be calculated with combination of cyclomatic complexity and lines of code metric results.

Maintainability IndexRisk Evaluation
00  To 09Low maintainability
10 To 19Moderate maintainability
20 To 100Good maintainability

Example

  1. namespace CodeMetricsExample  
  2. {  
  3.     class Program  
  4.     {  
  5.         static void Main()  
  6.         {  
  7.         }  
  8.     }  
  9. }  

CODE METRICS

Cyclomatic Complexity

Cyclomatic complexity helps us by measuring the code complexity. The cyclomatic complexity metric is quite important because it'll be calculated on method level. So developers can easily identifying complexity of the code and risk factors in method level. 

Cyclomatic Complexity

Risk Evaluation

>50

Very high risky code which is an un testable

21 To 50

Risky code it include more complex logic

11 To 20

Moderate risk

1 To 10

a simple program, without very much risk


Example

See the below code and run a metric for that. I got the result as cyclomatic complexity is 12 for just of 5 lines of code. 

  1. private static void GetFormattedEmployeeDetails(Employee employee)  
  2.   {  
  3.       if (employee != null)  
  4.       {  
  5. if (string.IsNullOrWhiteSpace(employee.FirstName) && string.IsNullOrWhiteSpace(employee.LastName))  
  6.                 {  
  7.                     //Build full name  
  8.                 }  
  9.                 if (string.IsNullOrWhiteSpace(employee.Address1) && string.IsNullOrWhiteSpace(employee.Address2) &&  
  10.                 string.IsNullOrWhiteSpace(employee.Address3) && string.IsNullOrWhiteSpace(employee.City) &&  
  11.                 string.IsNullOrWhiteSpace(employee.Country) && string.IsNullOrWhiteSpace(employee.Zipcode))  
  12.                 {  
  13.                     //Build complete address  
  14.                 }  
  15.                 if (string.IsNullOrWhiteSpace(employee.Email))  
  16.                 {  
  17.                     //Check Valid Email..Regex check  
  18.                 }  
  19.                 if (string.IsNullOrWhiteSpace(employee.Phone))  
  20.                 {  
  21.                     //Do Something  
  22.                 }  
  23.             }  
  24.  }  

CODE METRICS

Just imagine, if you add some more logic, complexity will be increased. To rectify this bad code, we have to refractor the code.

CODE METRICS

I refactored my code into a small number of portions as shown. Now cyclomatic complexity is only 2 for same 5 lines of code.

  1.       static void Main()  
  2.       {  
  3.           Employee employee = new Employee();  
  4.           GetFormattedEmployeeDetails(employee);  
  5.       }  
  6.       private static void GetFormattedEmployeeDetails(Employee employee)  
  7.       {  
  8.           if (employee != null)  
  9.           {  
  10.               FullEmployeeName(employee);  
  11.   
  12.               GetCompleteAddress(employee);  
  13.   
  14.               IsValidEmail(employee);  
  15.   
  16.               GetPhone(employee);  
  17.           }  
  18. }  

CODE METRICS

Depth of Inheritance

Depth of inheritance describes the number of classes from which a specific type inherits functionality. The idea is that if more types exist in an inheritance hierarchy, the code will likely be more difficult to maintain as a result.

Depth of InheritanceRisk Evaluation
>4Base types are critical
3 To 4Base types are still okay
1 To 2Base types are good

Class Coupling

Class coupling is a measure of how many dependencies classes in a single class uses.

Class CouplingRisk Evaluation
> 30 (on member level) AND > 80 (on type level)Dependencies are critical
10 To 30 (on member level) AND 10 To 80 (on type level)Dependencies are still okay
00 To 09Dependencies are good

Example

The Program class has dependency with employee class, so class coupling is 1. 

  1.        static void Main()  
  2.        {  
  3.            Employee employee = new Employee();  
  4.            GetFormattedEmployeeDetails(employee);  
  5. }  

CODE METRICS

The below Program class has dependency with employee class and EmployeeBusinessService class, so class coupling is increased to 2.

  1. static void Main()  
  2.         {  
  3.             Employee employee = new Employee();  
  4.             EmployeeBusinessService employeeBusinessService = new EmployeeBusinessService();  
  5.             GetFormattedEmployeeDetails(employee);  
  6.             employeeBusinessService.SaveEmployee(employee);  
  7.  } 

CODE METRICS

Line of Code

The fewer the lines of code in a method, the more maintainability it has. This metric will be calculated at method level and calculation is not the exact line of code we write in C#, it is actually based upon the line number of IL code.  The calculation does not include comments, white space, line break etc.

Lines of CodeRisk Evaluation
>20Lines of code is critical
11 To 20Lines of code is still okay
1 To 10Lines of code is good

Example

The below code snippet has comments and white spaces. If you ran a metrics, lines of code result is 4. 

  1. static void Main()  
  2. {  
  3.     //Employee object have employee related details   
  4.     Employee employee = new Employee();  
  5.   
  6.     EmployeeBusinessService employeeBusinessService = new EmployeeBusinessService();  
  7.       
  8.     //Validate the complete employee object and get formatted employee details  
  9.     GetFormattedEmployeeDetails(employee);  
  10.   
  11.     //Save employee details   
  12.     employeeBusinessService.SaveEmployee(employee);  }

CODE METRICS

Additional Tools

  1. Tool For Maintainable Index
    Microsoft Code Lens Code Health Indicator is a free extension. This feature will provide the quick information about your code. It means provide code maintainable index on the fly for the methods, properties or classes.

    CODE METRICS

  1. Tool For Cyclomatic Complexity
    This is a Code Metrices  which helps to monitor the code complexity. As you type, the method complexity "health" is updated, and the complexity is shown near the method.

    CODE METRICS
  1. Identify Duplicate Code using Code Clone Analysis
    The Code Clone Analyzer in Visual Studio helps us to search duplicate code in the entire project but this is only for Visual Studio Enterprise users.

    Analyze Menu –> Analyze Solution for Code Clones
  1. NDepend
    It’s great tool which provides several additional metrics like number of methods, number of fields, number of variables in class and etc.
  1. SonarQube
    It’s another great tool for inspecting code quality and can be used for performing Code Reviews as well.

Conclusion

By taking advantage of these metrics, as a developer, you can understand which classes, which methods, which module should be reworked or refractor. You can identify complexity, potential risks, implementation flaw within your project.

As per my experience, if you'll follow coding principles properly like SOLID, DRY, KISS and YAGNI, you can achieve good metrics results.


Similar Articles