NDepend - A Complete Static Code Analysis Tool

Visual Studio provides StyleCop and FxCop for code analysis which gives C# Coding guidelines, but there is one more tool from Visual Studio which gives the quantitative measure of coding guidelines in terms of Cyclomatic Complexities, Maintainability Index, and a lot more. This article explains each term in-depth and lets you understand their usage in the application.
 
A few months ago, I came across one static code analysis tool named NDepend and found this to be the next level. It is way richer in functionalities and offers a lot of parameters and graphs, visualizations, which definitely can make developers’ and architects’ life easier.
 
Before going further, let us start from the beginning.
 

What is a Static Code Analysis?

 
Static code analysis is a stage of development where we take care of code quality. It works as an early warning system for code being developed and prevents future disasters. As a developer, we make many mistakes while developing and that could be a result of a tight schedule, work pressure, less experience of the team, not understanding of standard application guidelines, and many more.
 

What is NDepend?

 
NDepend is a Visual Studio extension that works with all versions of Visual Studio starting from 2010 and it supports major .NET versions i.e. .NET Framework 4.x, .Net Core 3.1, and ASP.NET Core 3.1.
 
In addition to this, it supports CI Integration and Azure DevOps too.
 
 
NDepend Branding
 
How to install NDepend?
 
It comes as a Visual Studio Extension VSIX file and is very easy to install. Just a few easy clicks and you can get into the world of amazing features.
 
How to Access NDepend Metrics?
 
It can be accessed directly by right-clicking on the solution or from top menu bar like this –
 
Accessing NDepend in Visual Studio
 

How does NDepend help in Static Code Analysis?

 
We saw in the previous article on Calculate Code metrics which gives the values of various metrics, while NDepend heavily relies on visualization. They are many but here are some, which I thought they are essentials.
 

Dashboard

 
This is the first screen when you run the NDepend for any solution.
 
NDepend: Dashboard
 
It gives the following information
  • Lines of code
  • Assembly related detailed information.
  • Comment percentage and many things.
  • We will be learning about the other parameters on the dashboard in the coming sections.2. NDepend Dependency Graph
Again, you access this from the tab and it gives this screen with tons of information. Some of them are listed here
 
NDepend – Dependency Graph
  • The size of any node can be set based on many parameters like complexity, Lines of code, and many more.
  • The thickness of the edge also can be adjusted based on namespace, methods, type, and fields.
  • It shows the complete relationship between the types in the solution.
  • Files or directories can be dragged and dropped in Visual Studio and it will show the relationship among them.
  • Any node can be searched and added here and if not required in the graph, can be easily removed. (for example – we can get rid of .NET framework related libraries while analyzing the custom code)
  • Other than searching, it also provides a feature of filtering and grouping of elements.
  • When two nodes and linking edge are clicked together, it gives the coupling matrix and coupling graph.
Clicking on any nodes, gives complete information about the relationship, as shown here,
 
NDepend – Dependency Graph
 

Dependency Matrix

 
Dependency Matrix looks like this. Any cell can be expanded and we can see the dependency between any these two at any level. The main objective of this matrix to visualize and see the coupling.
 
NDepend – Dependency Matrix
  • It shows the dependency between any two code elements.
  • Dependency can be based on these parameters – namespace, types, member, methods, fields, direct and indirect depth of use.
  • When you click on any cell, it gives you more detailed information about dependency between these two code elements. For example – we see here the in-depth dependency between Common and Client.Infrastructure namespaces.
NDepend – Dependency Matrix
 
This Dependency matrix also gives a very good view of coupling in terms of method calls, with the setting Weights on cells = Direct # Method. As shown here in a red box,
 
NDepend – Dependency Matrix
 

Code Matrix Visualization

 
In the Metrics View, the code base is represented through a Treemap. Treemapping is a visualization algorithm for displaying tree-structured data by using nested rectangles.
 
Here it follows the hierarchy order of assembly, namespace, type, method, and then fields. This is an example from the code, which I was using.
 
NDepend – Dependency Matrix Visualization
 
Again, the size of the rectangle can be seen based on more than 10 parameters, shown in the navigation bar.
 
NDepend – Dependency Matrix Navigation Bar
 
Now let us try to understand the options by looking closely into navigation bar,
  1. What are you trying to show in all of the treemaps? Options are Assembly, Namespace, Type, Method, and fields. Since it follows the hierarchy, it will show everything the rectangle beginning Assembly to what you have chosen from dropdown. (e.g. – I have selected Method, so it shows Assembly, Namespace, Type, and Method)
  2. Items in this drop-down control the size of the rectangle chosen from field #1.
  3. How many selected code items will be shown in each rectangle.
  4. 4 will open the help page with the definition of parameters.
  5. We can be used to switch among colors for different elements.
  6. It shows the selected item in the rectangles.
  7. It will select the number of items to be shown.
  8. Next button to 7, opens up the help page of the definition of parameters.

Abstractness vs. Instability

 
This is another very useful visualization that shows the useless and painful code in the solution. For example, I have run the same for two projects.
 
Project # 1 has few codes in the zone of uselessness while Project # 2 seems totally fine.
 
 
NDepend – Abstractness and Instability
 
We need to understand the following two most important points about this graph,
  • Assembly having a large number of concrete classes, static classes will fall in the zone of pain because in the future they may be difficult to manage and maintain.
  • Any assembly having a large number of interfaces and abstract falls into the zone of uselessness.
Technical Debts
 
First, let us see the definition of Technical Debt as this will help to understand this section in a better way,
 
In this metaphor, doing things the quick and dirty way sets us up with a technical debt, which is similar to financial debt. Like financial debt, the technical debt incurs interest payments, which come in the form of the extra effort that we have to do in future development because of the quick and dirty design choice. We can choose to continue paying the interest, or we can pay down the principal by refactoring the quick and dirty design into the better design. Although it costs to pay down the principal, we gain by reduced interest payments in the future.
Martin Fowler
 
In line with this definition, NDepend provides a fantastic mechanism to calculate Technical Debts and Technical Interests. It has default formulas and that can be customized whenever needed. We can see it in the given example with 7 points,
 
 
Point # 1 – In Dashboard, Debt box shows the estimated efforts needed to complete the debts. In the right pane, it shows the issues and their summed efforts.
 
Point # 2 – In the right pane, it shows the technical interest in the issues. i.e. – if these issues are NOT fixed, over time, it will keep on adding on and will get bigger on issues.
 
Point # 3 – This field shows the total efforts needed to code the whole system from scratch.
 
Point # 4 – Debt percentage is Debt effort * 100/ Total Development Effort.
 
Point # 5 – IT shows the code coverage for testing. In this case, there is nothing on this.
 
Point # 6 – This helps in prioritizing the issues to fix first based on their severity. It is again a very useful block.
 
Point # 7 – Breaking point is the point when Technical interest becomes equal to Technical debts. In the given example, it is very little here as those issues are very small.
Since it was a demo project, I couldn’t explore this functionality much, but I found it very interesting and significant in any software development set up. Based on my findings, I thought of adding these important points about this amazing feature
  • Based on the percentage of Debt, it can be categorized in A, B, C, D, and E, where A being the minimum (1%-5%) and E is for over 50%.
  • Issues are categorized as Blocker, Critical, High, Medium, and Low. Again, this can be customized.
  • For the legacy project, we can set the baseline dates, hence Technical debts will be shown only after that, not for the whole project in its lifetime.
  • By Default, Tech Debts are in form of time but that can be changed to a money value, just with few settings.
Some more important features of NDepend,
 
Code Rule, Code Query with C# LINQ
 
A CQLinq query is a type of LINQ query that relies on types defined in the namespace NDepend.CodeModel. All code rules are created using this only. Some code rules are by default and new code rules can be written to get the code smell. This is there to ensure the code quality and subsequently for Technical Debts assessment.
 
Quality Gate and Build Failure
 
Quality gates are some special types of code rules, written to prevent any critical issue which can lead to costly technical debts.
 
Using NDepend API
 
NDepend.API it is easy to programmatically,
  • Analyze one or several .NET assemblies and create NDepend reports (only with Build Machine licensing)
  • Explore dependencies between these assemblies’ namespaces, types, methods and fields
  • Gather usual code metrics, computed by NDepend on code elements, and create your own code metrics
  • Explore diff between two versions analyzed of a .NET codebase, and even follow evolution across many versions
  • Open source file declaration(s) of a code element
  • Generate on the fly and execute CQLinq rules or queries
With this, I have tried to get you an overview of the NDepend tool and I have covered most of the features, but still, many features are still left. If you want to try to explore all the features of NDepend, it is a 14 days free trial.
 
I sincerely thank Patrick Smacchia for this amazing tool and for giving me an opportunity and ample time to explore the amazing tool in depth. 
 
Before concluding, I will reiterate that this was on the demo project so I couldn’t explore some of the features in more detail as they are time dependant but my experience is – The more you use this, the more you will love this. It is a complete static code analysis tool. Try with 14 days trial and let me know if you too feel the same?
 
Originally published on taagung.
 
References
  • NDepend Documentation
  • Source code