C# Static Code Analysis with NDepend

NDepend Icon
Have you heard about the “goto fail” fail? This is a security bug which was introduced by Apple in one of the iOS updates. Long story short, there was a piece of unreachable code which had to perform an important security check of a certificate. But it was unreachable. This is a huge defect in the software of this kind. Any meaningful static analysis tool would find that defect and any meaningful developer would fix such a bug after that. What am I talking about is that the cost of lately caught bugs is much greater than the cost of a bug caught at compile time. I don’t know how the hell Apple slipped up like that, but we are not going to discuss that. We are going to talk about static analysis.

So, what is static code analysis in essence? Roughly speaking, any analysis without actually running the code can be considered static. If you run the code, click here and there, see the result, estimate it and then fixing the problem (if there is one), then you’re actually doing a Reactionary Inspection or Dynamic Analysis.

Have you ever thought that actually we require passing arguments into a constructor in order to set the class using preconditions with the intention to spawn compile errors in case of incorrect instantiation of that class? Sounds strange, but it is at least partially true. Sometimes, developers hide dependencies and as a corollary, the client code fails in the runtime. Experienced programmers try to shorten the feedback loop as much as possible (though, there are always some tradeoffs). It’s too expensive to catch all bugs in the runtime. And here into play come static analysis tools.

What’s going on nowadays?

There is plenty of tools which perform static analysis in one form or another. Some of them have the primary goal to check the code quality. The other provides this feature as a secondary one.

Let’s take a brief look at not a full list (I’m sure) of static code analysis tools:

Actually, I’ve taken this list from stackoverflow.com and made it shorter by removing old and non-competitive tools. If I’m wrong you can add a comment.

I’ve been using ReSharper since its fifth major release. I always though that R# is a very strong tool which helps to keep your code base as cleanest as possible. Nowadays R# provides static analysis features regarding many aspects of code quality, and I’m talking about serious flaws, rather than naming styles and removing of unused imported namespaces. But I should admit that it is not a primary goal of R#. It is more about refactoring and navigating. In short, it is a productivity tool. I think that R# is outstanding and actually out of competitiveness in this field. Thus, ndepend vs resharper is a nonsensical topic.

Introducing NDepend

I wanted to get a little bit deeper into the serious static analysis, so I decided to take a look at NDepend. NDepend is a mature tool with its own history which traces back to 2004. This tool is all about monitoring the health of an application. I consider the following features of NDepend as the most interesting:

  • Code Rules for checking compliance with best practices.
  • CQLinq (Code Query over LINQ) language to query your code base. Very cool feature for analysis customization!
  • 82 code metrics of Code Quality.
  • Various Charts and Diagrams for Monitoring process. I think these features taking together become a killing one. This point in conjunction with the previous two is what makes NDepend a tool for tracking the health of a software product in a long run!
  • NDepend takes care of the architecture by allowing you to explore the dependencies between modules and how they are structured.
  • Enforced Immutability and Purity. Nowadays functional programming becomes very popular and this NDepend feature goes accordingly to this trend.
  • NDepend 6 integrates with Visual Studio (including VS 2010, 2012, 2013, 2015) and can be integrated with your build process.
  • It provides the API on top of which you can build as many custom inspections as you like. So, NDepend is not a black-box despite it is not an open-source.

There are other features like comparing builds and code diff which is all about versions comparing, analyzing of test coverage. Different people have a different experience, so they will have different priorities regarding features.

NDepend Working Modes

After installing NDepend you’ll find in its folder:

  • NDepend.Console.exe can be used for integration with a build process.
  • NDepend.PowerTools is a bunch of open-source static analyzers based on NDepend.API.You can use them through the NDepend.PowerTools.exe console program which goes with NDepend setup bundle. You can launch it and use utilities through a command line.
  • VisualNDepend is a separate UI-client which supports all NDepend features.
  • NDepend.VisualStudioExtension.Installer is an installer of a VS-plugin.

You can explore the source code of PowerTools in NDepend.PowerTools.SourceCode folder. This can help you to understand the API of NDepend.

The most common way to use NDepend is through the Visual Studio plugin.

NDepend in Action

To start using NDepend you can create NDepend project and include projects/libraries which you want to analyze.

After that, NDepend will start analyzing the code base and in the end, you’ll get the results.

For my pet project I’ve got the following result:

DashboardRules

NDepend found enough problems in my code. Some of them are really helpful. I like that NDepend found 10 classes which can be changed to structures. Structures are extremely effective from the memory pressure perspectives. This is especially important when we’re talking about mobile applications.

NDepend found some low-cohesive classes which should be refactored out. Also, it found some long methods and many other less important flaws.

The important thing I want to mention is a customization. I’ve heard many times from people something like, “I installed FxCop and it found hundreds of defects. Many of them are discussable, so I just removed FxCop, because I don’t want to spend much time on figuring all it out.” Well, the “problem” of all tools like R#, FxCop, StyleCop, NDepend et.c. is that they all use heuristics here and there. Only you can define heuristics precisely for your organization. So, you’d have to spend some time for customizing such tools in case you decided to rely on them.

You can customize NDepend metrics by using CQLinq. CQLinq looks like this:

// <Name>Structures should be immutable</Name>
warnif count > 0 from t in Application.Types where
t.IsStructure &amp;&amp;
!t.IsImmutable

let mutableFields = t.Fields.Where(f => !f.IsImmutable)

select new { t, t.NbLinesOfCode, mutableFields }

As I’ve already mentioned CQLinq is based on LINQ, so the syntax should be very familiar for any .NET developer.

NDepend can build beautiful visualizations. Look at size of instances:

instance sizes

Another advantage of NDepend is that it doesn’t consume tons of memory and doesn’t influence on performance badly. For example, R# tremendously deteriorates the performance of VS.

Conclusion

NDepend is a very powerful tool to keep applications healthy over a long period of times. This is not a toy tool which you can grasp in one day, so you’ll have to invest some time into learning it.

I want to recommend a pluralsight course on NDepend “Practical NDepend” by Eric Dietrich as a great NDepend tutorial. If you don’t have paid access to Pluralsight you can request a free trial on 15 days (if I recall correctly) or download this course from the Web (if your conscience allows). You can significantly simplify and boost the learning process of NDepend.

One last important thing I want to mention is that NDepend is not a free tool and I don’t know if there is a full-fledged NDepend free alternative. Professional NDepend license price is not extremely high in my opinion, just look at the official site for more information.