Analyze your code using NDepend – Part 1

Whether you have to get on-board on an existing .NET project or you want to get an overview of your own project and use a more holistic approach to code improvement, you will quickly reach the limit of the tools provided by default in Visual Studio. Fortunately, Visual Studio (like most major development environment) does provide a good way to extend it and over time quite a few third-party tool vendors have started providing additional functionality for your favorite IDE.

One such tool is NDepend. The goal of NDepend is to first provide you with means to browse and understand your code using better a better visualization than what’s available by default in Visual Studio. But NDepend allows you to go further than that. Let’s have a look at how you can improve your code and manage code improvement using this tool.

Disclaimer: I was asked by the creator of NDepend whether I’d be interested in test driving it and sharing my experience on my blog. But the reason why I accepted writing this article is that NDepend has helped me improve the code quality in one of my project and I feel this is a tool with a lot of potential. I do not work for NDepend neither do I get any financial compensation from them (except for a free license for the tool).

Download and Installation

You can download a trial version of NDepend on their web site. The installation process is pretty straightforward. You download a ZIP file; extract it to some directory and start the installation executable. If you have a license for it, you just need to save the license file to the same directory where you’ve extracted the ZIP file.

During the installation process, the installer will identify which Visual Studio versions (it supports VS 2008 till VS2013) are installed and allow you to install NDepend as an add-in. One thing I really like was that I was able to install it and activate it (over the menu Tools | Add-in manager) with needing to restart Visual Studio.

Once you’ve activated NDepend, a new menu item will be available in your menu bar. A good place to start is the Dashboard.

Dashboard

The Dashboard shows you an overview of all relevant metrics related to your project as well as their evolution over time:

NDepend Dashboard

It shows some general project metrics like:

  • Number of lines of code
  • Number of types
  • Percentage of lines of comment
  • Max and average Method Complexity
  • Code Coverage
  • Usage of assemblies

But also some metrics related to coding rules. These code rules violations are clustered in critical and non-critical rules. All these metrics are available either as a view of the current status or as a graph showing you the evolution over time. Very often, especially when using NDepend on a project, which has already been around for some time, it is not possible to fix all violations at once and it’s important to be able to see whether we’re slowly reducing the number of violations or whether we have a negative dynamic and the number of violations are actually increasing.

All diagrams can be exported to HTML. This makes it easy to incorporate it in external reports about your project. If like me you’re stuck with an older version of Internet Explorer, you might get an almost empty display when looking at the exported web page. You then just have to open it in another browser. It’d be nice if it also worked in IE8 but let’s face it, web technologies keep evolving at a high pace and you can’t really expect anything to work in a browser, which is already more than 5 years old…

Code Rules

One of the most valuable features in NDepend is that all code rules are based on queries on a model. This means that you can adapt them, as you need i.e. in order to change a threshold or consider additional criteria. So you can adapt existing rules (the ones provided with NDepend) but also add your own rule groups and queries. Of course, that’s something you will only be able to use once you’ve invested enough time in learning how NDepends works. But modifying an existing rule is very easy.

Just as an example: There is a rule called “Methods too big”. It basically scans for methods with more than 30 lines of code. Let’s say, you define that in your project, it’s fine having methods of up to 40 lines of code. You can just click on one of the links in the “Code Rules” widget of the Dashboard:

NDepend Dashboard Code Rules

It will open the Queries and Rules Explorer. On the left hand side, you’ll see all rule groups:

NDepend Dashboard Code Rules Groups

There you can also create some groups or delete them. You also immediately see whether any of the rules in a group returned a warning or not. When you click on one of the groups, you’ll see all related queries on the right hand side:

NDepend Dashboard Code Rules queries

Queries can be activated and deactivated. And you can open the queries and rule editor by clicking on one of the queries.

The editor is a split pane, with the query on the top e.g. in the case of “Methods too big” you will see the following code:

// <Name>Methods too big</Name>
warnif count > 0 from m in JustMyCode.Methods where 
   m.NbLinesOfCode > 30
   // We've commented # IL Instructions, because with LINQ syntax, a few lines of code can compile to hundreds of IL instructions.
   // || m.NbILInstructions > 200
   orderby m.NbLinesOfCode descending,
           m.NbILInstructions descending
select new { m, m.NbLinesOfCode, m.NbILInstructions }

// Methods where NbLinesOfCode > 30 or NbILInstructions > 200
// are extremely complex and should be split in smaller methods.
// See the definition of the NbLinesOfCode metric here 
// http://www.ndepend.com/Metrics.aspx#NbLinesOfCode

And below you will see where a match was found. You will notice that when the violation occurs in an auto-property setter or getter, it is not possible to jump to this line of code by clicking on the link. When asked, the NDepend support answered that the problem is that the PDB file doesn’t provide this info and hence NDepend doesn’t know about the location. So though I do hope that they find a solution for this in the future, you can work around it by clicking on the type name and navigating to the appropriate location. Since none of us should have types with thousands of lines of code, it is no big deal, right? ­čśë

All queries I’ve looked into seemed to be very well commented. This made it easy to understand what the rule is about and how to modify it to comply with one’s coding rules.

So in our example, in order to change the threshold for the “Methods too big” query, all you need to do is replace 30 by e.g. 40 and save. Additionally, you can press the “Critical” button to mark this rule as a deal breaker i.e. when called during a build, it will return an error code so that you can refuse to build the software if some critical violations are detected (of course I doubt you’ll use it with a “Method too big” violation).

The NDepend online documentation provides a lot of useful information about the query language. Since it’s based on the C# LINQ syntax, you’ll need to be comfortable with LINQ in order to start working with custom rules. But I guess most developers and architects working with C# are familiar with LINQ anyway…

Trend charts and Baselines

Except for the ability to customize and extend the NDepend rule set, another thing I found very useful is the ability to create and work with trend charts. The ability to create baselines for comparison is also a nice feature related to this topic.

Whenever you start working with static code analysis on a project which has already been around for quite some time, you end up getting a huge list of findings. It’s rarely the case that you can fix them all in the short term. What’s really important is to fix the critical violations and make sure that you first do not introduce more violations as your code evolves and also with every new version try and reduce the number of violations (starting with the most important ones).

Trend Charts

In order to create a trend chart, click on the “Create Trend Chart” button at the top of the Dashboard. The following dialog will appear:

NDepend Create Trend Chart

You can give your new trend chart a name choose which series will be defined and how they should look like. Once you save your new trend chart will be displayed in the dashboard.

A few useful trend charts are already displayed by default in the Dashboard:

  • Lines of Code
  • Rules Violated
  • Rules Violations
  • Percentage Coverage by Tests
  • Maximum complexity, lines of code, number of methods for a type, nesting depth…
  • Average complexity, lines of code, number of methods for a type, nesting depth…
  • Third-Party Usage

Using these trend charts, it’s dead easy to get an overview whether you’re going in the right direction or keep making your software more complex and error-

More about how I use NDepend┬áto analyze and improve my code will come in a follow-up article…

 

Leave a Reply

Your email address will not be published. Required fields are marked *