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
- 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.
- Identify the complexity and maintainability of your code
It’ll give you an insight of your code maintainability and complexity.
- 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.
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 Index | Risk Evaluation |
00 To 09 | Low maintainability |
10 To 19 | Moderate maintainability |
20 To 100 | Good maintainability |
Example
- namespace CodeMetricsExample
- {
- class Program
- {
- static void Main()
- {
- }
- }
- }
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.
- private static void GetFormattedEmployeeDetails(Employee employee)
- {
- if (employee != null)
- {
- if (string.IsNullOrWhiteSpace(employee.FirstName) && string.IsNullOrWhiteSpace(employee.LastName))
- {
-
- }
- if (string.IsNullOrWhiteSpace(employee.Address1) && string.IsNullOrWhiteSpace(employee.Address2) &&
- string.IsNullOrWhiteSpace(employee.Address3) && string.IsNullOrWhiteSpace(employee.City) &&
- string.IsNullOrWhiteSpace(employee.Country) && string.IsNullOrWhiteSpace(employee.Zipcode))
- {
-
- }
- if (string.IsNullOrWhiteSpace(employee.Email))
- {
-
- }
- if (string.IsNullOrWhiteSpace(employee.Phone))
- {
-
- }
- }
- }
Just imagine, if you add some more logic, complexity will be increased. To rectify this bad code, we have to refractor the code.
I refactored my code into a small number of portions as shown. Now cyclomatic complexity is only 2 for same 5 lines of code.
- static void Main()
- {
- Employee employee = new Employee();
- GetFormattedEmployeeDetails(employee);
- }
- private static void GetFormattedEmployeeDetails(Employee employee)
- {
- if (employee != null)
- {
- FullEmployeeName(employee);
-
- GetCompleteAddress(employee);
-
- IsValidEmail(employee);
-
- GetPhone(employee);
- }
- }
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 Inheritance | Risk Evaluation |
>4 | Base types are critical |
3 To 4 | Base types are still okay |
1 To 2 | Base types are good |
Class Coupling
Class coupling is a measure of how many dependencies classes in a single class uses.
Class Coupling | Risk 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 09 | Dependencies are good |
Example
The Program class has dependency with employee class, so class coupling is 1.
- static void Main()
- {
- Employee employee = new Employee();
- GetFormattedEmployeeDetails(employee);
- }
The below Program class has dependency with employee class and EmployeeBusinessService class, so class coupling is increased to 2.
- static void Main()
- {
- Employee employee = new Employee();
- EmployeeBusinessService employeeBusinessService = new EmployeeBusinessService();
- GetFormattedEmployeeDetails(employee);
- employeeBusinessService.SaveEmployee(employee);
- }
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 Code | Risk Evaluation |
>20 | Lines of code is critical |
11 To 20 | Lines of code is still okay |
1 To 10 | Lines 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.
- static void Main()
- {
-
- Employee employee = new Employee();
-
- EmployeeBusinessService employeeBusinessService = new EmployeeBusinessService();
-
-
- GetFormattedEmployeeDetails(employee);
-
-
- employeeBusinessService.SaveEmployee(employee); }
Additional Tools
- 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.
- 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.
- 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
- NDepend
It’s great tool which provides several additional metrics like number of methods, number of fields, number of variables in class and etc.
- 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.