Search code examples
c#code-metrics

Script to calculate Uncle Bob's "Agile PPP" code metrics for C#


I am reading Agile PPP for C#, and at some point Uncle Bob presents interesting metrics for design quality:

These are:

  • H (relational cohesion) = (R + 1) / N, where:
    • R = number of internal relations inside a component;
    • N = number of classes inside that component.
  • I (Instability) = Ce / (Ca + Ce), where:
    • Ca = afferent couplings;
    • Ce = efferent couplings;
  • A (Abstractedness) = Na / Nc, where:
    • Nc = number of classes;
    • Na = number of abstract classes;
  • D' (normalized Distance from main sequence) = abs(A + I - 1) / sqrt(2), where:
    • "main sequence" is, inside an A vs I cartesian plot, the diagonal line formed by the positions where A + I = 1;

The most intriguing part is this (directly from the book):

The metrics we describe have been successfully applied to a number of projects since 1994.

Several automatic tools will calculate them for you, and they are not difficult to calculate by hand.

It is also not difficult to write a simple shell, Python, or Ruby script to walk through your source files and calculate them.

For an example of a shell script, you can download depend.sh from the freeware section of objectmentor.

I couldn't find this depend.sh script, and I'm not sure if I agree that these metrics are easy to calculate by hand, or via some script (I would like to use Python for that, if that was the case).

So, the questions are:

  • Is there a free tool or script to calculate Uncle Bob's metrics for C# code? Visual Studio has some metrics, but they are different, and I don't really know or care how to interpret them;
  • How should I approach the task to build my own script There is the famous "regex can't parse html" fact, and I wonder if C# code structure lends itself to the sort of "simple script" Uncle Bob is proposing, so that these metrics can be calculated. Should I even try?

Solution

  • The tool NDepend computes these metrics and it makes easy to write your custom metrics through C# Linq Queries.

    It is integrated in Visual Studio and also generates report with Uncle Bob's metrics diagram.

    A 14-day trial full featured edition is available for download.

    NDepend Uncle Bob's metrics diagram