Quality

Lines of code, cyclomatic complexity, coupling, cohesion, code coverage. You’ve probably heard about these metrics before. But do you actively track them? Should you? Visual Studio computes some of these metrics out of the box. But if you want to define a custom metric, you’re out of luck. Yet, there are a bunch of code metrics that you might find useful for your code base. More so, a composite metric might be more helpful than the sum of its parts. For example, the C.R.A.P. Metric detects complex code that is not covered by unit tests. How can you track such a metric in Visual Studio? In this article we’ll see how to visualize code metrics, add custom metrics and how to monitor trends with NDepend.

Code Metrics

NDepend computes many metrics out of the box. You can use the intellisense support to discover the standard metrics for a given code element:

Computer Code Metrics

But it would be hard to extract information from these metrics if all we got was a bunch of numbers. We need other techniques to help us break down the complexity of the data. Visualization techniques complement metrics, by making it easier to synthesize and digest this information.

Continue Reading

Quality

Your code base has a lot to tell you. The question is: How can you listen to it? You can identify code smells when you’re reading code or extending it, but this doesn’t give you an overview. After you have been working for a while in a project, you can name some of its strengths and weaknesses. But this approach takes a long time, relies on experience and is subjective. It would be nice if you could query a code base in a structured way. Basic search functionality from an IDE like Visual Studio isn’t powerful enough. NDepend allows you to query .Net code using LINQ syntax through CQLinq – Code Query LINQ. In this blog post we’ll discuss how to query your code base using CQLinq.

An Example

Since I like to learn from examples, let’s first see a simple, yet very powerful query. The following code detects classes that are candidates to be turned into structures. This is one of the default CQLinq rules.

from t in JustMyCode.Types where
  t.IsClass &&
 !t.IsGeneratedByCompiler &&
 !t.IsStatic &&
  t.SizeOfInst > 0 &&

  // Structure instance must not be too big,
  // else it degrades performance.
  t.SizeOfInst <= 16 &&
  // Must not have children
  t.NbChildren == 0 &&

  // Must not implement interfaces to avoid boxing mismatch
  // when structures implements interfaces.
  t.InterfacesImplemented.Count() == 0 &&

  // Must derive directly from System.Object
  t.DepthOfDeriveFrom("System.Object".AllowNoMatch()) == 1 &&

  // Structures should be immutable type.
  t.IsImmutable
select new { t, t.SizeOfInst, t.InstanceFields }

As you can see, the query is quite readable. Even if you don’t know the CQLinq syntax, you understand what it does. And since it’s based on Linq, it already seems familiar.

Continue Reading