Increasing Code Quality of .NET Applications with NDepend

Hi, everyone.

I was planning to write a blog post for a long time about code analysis tools, which is obviously to improve the code quality of our projects. But, I couldn’t find the available time. A few months ago, I had the chance to get a free license of the NDepend. This tool helps to continuously improve the quality of our .NET applications in a wide range of contexts.

By the way, thanks for the free license to Patrick from NDepend.

So, I wanted to share how NDepend could help us to improve our code quality continuously.

Firstly, what is Code Quality?

Most of the time, we usually do maintain the continuity of an existing project and add new features. Therefore, when we start to look at the project, we often spend our time trying to understand the existing codes. As for me, “code quality” means understandable by other developers, easy to add new features, modular and flexible.

Actually, it couldn’t be right to say that there is only one reason for code quality. There are many factors in a software that directly or indirectly affect the code quality. For example, if we look with a developer’s viewpoint, when a developer writes clean codes instead of hard codes and chooses appropriate design principles to get the optimal solution, these would affect the code quality directly. From the viewpoint of the manager the development methodology, we use while developing a software, is one of the other factors that can indirectly affect the code quality. In addition, writing the software tests and documenting the software are among the other important elements.

Static Code Analysis

We said there wasn’t only one reason to improve code quality. I know, we usually trust to ourselves about the good coding. 🙂 But sometimes we may miss out some pain points. At this point, we need static code analysis tools to avoid these pain points and improve quality in our codes. Static code analysis tools analyze our codes with pre-determined rules and then provide some metrics to us such as (Code Coverage, Cyclomatic Complexity, Cohesion etc.) to improve our code quality.

My favorite point in this process is the ability to create Quality Gates based on project-specific rules. So, if our codes can’t pass the quality gates, the codes can’t commit to source control. Many software development teams do not like this process, I know, but this process can finally end some of the discussions in the teams.

There are many tools on this way that can be used. I have used StypeCop, ReSharper and Sonar in my previous company. Some of these tools can work in integrated mode with Visual Studio, while others can be included in builds in CI processes. In this article, we will look at the NDepend analysis tool.

Well, NDepend?

NDepend has been a mature Visual Studio analysis tool since 2004 to measure the health of our applications, improve code quality continuously, and simplify refactoring on legacy applications. It even calls “Swiss Army Knife” for .NET project teams.

If you look at the description on the NDepend‘s website:

NDepend is a Visual Studio tool to manage complex .NET code and achieve high Code Quality. With NDepend, software quality can be measured using Code Metrics, visualized using Graphs, Matrix and Treemaps, and enforced using standard and custom Rules. Hence the software design becomes concrete, code reviews are effective, large refactoring are easy and evolution is mastered.

NDepend is a commercial analysis tool, and you can use Visual Studio with the integrated mode or standalone mode. NDepend helps us to measure software quality using Code Metrics, Matrix and Treemaps, Standard and Custom Rules etc… Also, it provides us to measure technical-debt for our legacy applications using the Smart Technical Debt Estimation feature.

Some main features of NDepend:

  • Code Rule and Code Query over LINQ (CQLinq) (Great to customize the analysis operations. It also has CQLinq like a LINQ to query our code base.)
  • Smart Technical Debt Estimation
  • Quality Gates (I think it should be used)
  • Code Quality (82 Code Metrics)
  • Detect Dependency Cycles
  • Complexity and Diagrams
  • In-Depth Issues Management (Useful to control the technical-debt continuously.)

are some main features.

Now, we’ll run it in the standalone mode and look at some analysis result on a sample project.

NOTE: You can get 14 days free version of NDepend from here.

Let’s run the VisualNDepend.

Now, we need to click “Analyze VS solutions and VS projects” option from the left menu and choose the assemblies which we want to analyze. After this NDepend will analyze chosen the assemblies.

When NDepend complete analyzing of the assemblies, we can see it on the dashboard as like below:

From this dashboard, you can get the information how much technical debt do we have in the project, can we pass the quality gate, also we can see the complexity results of our methods quickly. As we can see the coverage result is empty. If we want to get coverage result, we have to import coverage data to NDepend such as “JetBrains DotCover“, “NCover” and “Visual Studio“.

Let’s take a look at the 11.94% debt. Firstly, click on the “C” result from the “Rating” part.

If we look at the menu, opened on the left side, it’s possible to see which class has how many issues and what are the estimation times of these.

It also possible to get different results and views by doing some changes in the above query with CQLinq query language of the NDepend.

// Types Hot Spots
from t in JustMyCode.Types
where t.AllDebt() > Debt.Zero && 
      t.AllAnnualInterest() > AnnualInterest.Zero
orderby t.AllDebt().Value.TotalMinutes descending
select new { t, 
   Debt = t.AllDebt(),
   Issues = t.AllIssues(), // AllIssues = {types issues} union {members issues}
   AnnualInterest = t.AllAnnualInterest(),
   BreakingPoint = t.AllBreakingPoint(),
   t.NbLinesOfCode,
   // t.PercentageCoverage,  to uncomment if coverage data is imported
   DebtRating = t.DebtRating(), 
   DebtRatio = t.DebtRatio() 
}

As we can see the above code block, it looks like a LINQ isn’t it? Actually this is a great thing especially for us.

Now we have to click on the 11.94% rate on the dashboard to able to see what kind of rules we have violated.

If we look at the menu on the left side, we can see the violated rules. At this point, my favorite part is, when I double click on the related rule, I can see the details.

Also NDepend has a dependency graph as follows:

NDepend shows us to metrics with a color metric visualization. For example: let’s follow to this path: “Metrics > Most Coupled > Type“.

NDepend makes it easy for us to see the type results that are most coupled by using the left side menu or the colorized visualization.

Build Process Integration

In my opinion, one of the most important things is that NDepend can be included into the build process. Many times it’s important to be able to specify quality gates during the build process and to interrupt the process when it necessary. It’s possible to integrate NDepend with Jenkins, TeamCity and TFS. It’s also fully compatible with SonarQube, which means that NDepend issues can be imported in the SonarQube issues set. So it’s possible to improve the code quality continuously. You can find detailed information about to the integration from here.

Conclusion

Obviously, I’m playing with NDepend for a while. (I also worked with NDepend team, it’s about dotless “i” character problem and that will be fixed with the next version.) In particular, I liked it because it works in the integrated mode with Visual Studio, and so before committing the codes to the source control, it allows us to see what happens in our local development codes, what rules we have violated, and it can also stop the commit operation. This process has been tried with SonarQube plugins in the company I’m working at, but if I’m not mistaken, we couldn’t get a very effective result. Anyway, NDepend is a useful tool that .NET developers can use to continually improve applications and write standardized quality codes.

https://www.ndepend.com
https://www.ndepend.com/features

Gökhan Gökalp

Recent Posts

Securing the Supply Chain of Containerized Applications to Reduce Security Risks (Policy Enforcement-Automated Governance with OPA Gatekeeper and Ratify) – Part 2

{:tr} Makalenin ilk bölümünde, Software Supply Chain güvenliğinin öneminden ve containerized uygulamaların güvenlik risklerini azaltabilmek…

5 months ago

Securing the Supply Chain of Containerized Applications to Reduce Security Risks (Security Scanning, SBOMs, Signing&Verifying Artifacts) – Part 1

{:tr}Bildiğimiz gibi modern yazılım geliştirme ortamında containerization'ın benimsenmesi, uygulamaların oluşturulma ve dağıtılma şekillerini oldukça değiştirdi.…

8 months ago

Delegating Identity & Access Management to Azure AD B2C and Integrating with .NET

{:tr}Bildiğimiz gibi bir ürün geliştirirken olabildiğince farklı cloud çözümlerinden faydalanmak, harcanacak zaman ve karmaşıklığın yanı…

12 months ago

How to Order Events in Microservices by Using Azure Service Bus (FIFO Consumers)

{:tr}Bazen bazı senaryolar vardır karmaşıklığını veya eksi yanlarını bildiğimiz halde implemente etmekten kaçamadığımız veya implemente…

2 years ago

Providing Atomicity for Eventual Consistency with Outbox Pattern in .NET Microservices

{:tr}Bildiğimiz gibi microservice architecture'ına adapte olmanın bir çok artı noktası olduğu gibi, maalesef getirdiği bazı…

2 years ago

Building Microservices by Using Dapr and .NET with Minimum Effort – 02 (Azure Container Apps)

{:tr}Bir önceki makale serisinde Dapr projesinden ve faydalarından bahsedip, local ortamda self-hosted mode olarak .NET…

2 years ago