Fun with NDepend, Part II: Creating Dependency Violation Warnings
Last time I gave a short overview over the features of NDepend. We know that NDepend can show a detailed dependency analysis your projects. This time I show you how you can write CQL queries to find out certain dependency violations.
Basic Dependency Operators
The CQL language has a bunch of ‘dependency’ operators, like IsUsing, IsUsedBy, IsDirectlyUsing , Implements etc. Those let you find out if a method/type/assembly is using a certain other methods/types/namespaces. Such an operator has most if the time a companion-operator, like DepthOfIsUsing, DepthOfIsUsedBy etc. A ‘dependency-depth” operator tells you if something is directly used or is a transitive dependency. Here’s example to explain that. Take a look at this small piece of code:
Use the IsUsedBy-operator on it and we get this result:
The DepthOfIsUsing tells us how directly an element is used. A value of 1 means that the code directly uses that element. In our example the Progam class directly uses the Visualisation class and hence the DepthOfIsUsing is one. The BusinessOperations is used by the Visualisation class, which is used by the Program class, therefore the depth is two and so on and so forth. The depth tells you over how many indirections something is used. This is very useful to filter out uninteresting relations. For example if you’re only interested in direct dependencies, then you can limit to a certain depth:
Update: Show Query Result as Depedency-Graph
This is quite a hidden feature: You can visualize results of a query as a dependency graph. We use the query from our example application. Run the query, then right-click on the header of the result and choose an visualization:
And the result:
A Real World Use Case
Now for what can we use this? Well with this we can create our own warnings. Let’s say we have a larger application which has three layers: The core-layer which contains stuff like database-connections, the business-logic layer which does all our complex logic and the presentation-layer which creates a nice user interface. Now we want to ensure that the presentation-layer never touches the database-stuff directly. For that we can write a little rule to check it:
After than we run NDepend. It will discover violations of our rules and display it as warning:
And of course tell you the exact code location which violates the rule:
Conclusion And Follow-Up
We’ve seen that we can use NDepend to write rules which enforce certain dependency rules. This allows us to spot quickly problematic usage of classes and interfaces in problematic places.
Next time I’ll try to integrate NDepend in my favorite continues build tool, TeamCity.
- Wolf Lake
- db4o Driver for LINQPad