Inspecting code quality with NDepend


Inspecting code quality with NDepend

Recently, I got the opportunity to review a very popular tool: NDepend. It has a lot of features, which can help you to navigate into a new solution, improve your legacy code, maintain good code quality, and so on, you can check them all here. In this article, we will start by reviewing an old project of mine (.NET Framework old), which I created some years ago while following a course.

The first thing we have to do is to attach an NDepend project to our solution. After it, we can start exploring our code and check where we can make improvements.

In the image above, we can see that our code is quite OK. I’d be slightly mad with my course otherwise, since it was supposed to be teaching me good practices. But anyway, we have some improvement opportunities here. Let’s start by investigating that critical rule violation.

To the left, we can see all rules that are checked, while to the right we can see our crimes. It seems that we are using non-readonly static fields. And it also mentions the number of times we have violated that rule. But what is this rule, and why is it bad to ignore it? By double-clicking on the rule, NDepend provides us with the information.

In my case, it was a pretty simple fix. As suggested, all I had to do was add the readonly modifier to it. Great! Let’s build our solution and run the analysis again.

We’re getting better! We can see our improvements regarding the baseline in the dashboard. We have reduced our technical debt to 1.79%, we don’t have any critical rule violations anymore, and we have reduced the number of issues by 6. Wait, 6? Didn’t I just say that we had only 3 violations of that rule? Let’s investigate it by clicking on this “-6” label.

I’ve included my old code so we can understand what was wrong. So, following the good practices and the analyzer rules, it is recommended that we mark fields with the readonly keyword whenever possible. But for static fields, it becomes even more important. So although the rules are similar, they are not the same, and that’s why we were violating 2 rules in a single line.

And then, after fixing the remaining violations, our dashboard looks like this:

Pretty satisfying sight, right? In a real case scenario, these fixes could have taken days or weeks for us to finish, and that’s why it’s really important to maintain the quality high. The effort required to fix technical debt is much greater that the effort to maintain a healthy code base. And NDepend provides us with the tools to do it. I won’t cover it now, but you can read more about it here.

But the most important thing about following rules is learning from them, and we can learn a lot if we pay attention to their descriptions. In the next articles, we’ll cover more about NDepend’s functionalities and how it can further help us to develop.