28 Jun
2008

Active Conventions with NDepend

Some time ago Patrick Smacchia wrote a nice article on his blog about active conventions on your code base. I thought I tried this for myself and made up some interesting CQL queries.

Suppose we want to enforce a BDD naming convention for every SetUp method. Such methods should be named Establish_context. The following CQL constraint reports those methods that are not named consistently:

// <Name>NUnit SetUp methods that are not named consistently.</Name> WARN IF Count > 0 IN SELECT METHODS FROM ASSEMBLIES "MyProject.Domain.UnitTests", "MyProject.Infrastructure.UnitTests" WHERE HasAttribute "NUnit.Framework.SetUpAttribute" AND !NameIs "Establish_context()"

Lets have another one. A while ago, I wrote this post about how WCF gave me this weird exception after I forgot to put a DataContract attribute on one of my DTO classes. Lets write another active convention for that:

// <Name>Data contracts without a DataContract attribute.</Name> WARN IF Count > 0 IN SELECT TYPES FROM NAMESPACES "MyProject.MyServiceContracts.DataContracts" WHERE !HasAttribute "System.Runtime.Serialization.DataContractAttribute"

Now here comes my personal favorite. Being the huge DDD adept that I am, I want to enforce that the domain is the core, the centerpiece, the kernel as you may of my application. I don’t want it to have any dependencies to other assemblies in my application, especially not the infrastructure assembly.

// <Name>Domain is directly using the infrastructure</Name> WARN IF Count > 0 IN SELECT METHODS FROM ASSEMBLIES "MyProject.Domain" WHERE IsDirectlyUsing "ASSEMBLY:MyProject.Infrastructure"

It can’t get any easier than this, now doesn’t it? This is actively enforcing Separation of Concerns. Another way to have a convention about this is the following:

// <Name>Domain-Driven Design convention</Name> WARN IF Count > 0 IN SELECT ASSEMBLIES WHERE AssemblyLevel > 1 AND NameIs "MyProject.Domain"

This means that my domain assembly can only have a reference to the .NET framework assemblies and nothing else. This gets my geek heart pounding.

Imagine the possibilities if you incorporate this with your daily and continuous integration builds. Pure software quality assurance if you ask me.

One thought on “Active Conventions with NDepend”

Comments are closed.