Thursday, June 25, 2009

How To: Build your own CodeRush Metric

Well it’s been a long time, but I think I’ve finally found something I can turn into simple plugin.
Note: This tutorial assumes that you are familiar with LINQ, are coding your plugin in VS2008 and targeting a system with .Net 3.5 installed.

We’re going to provide a count of the number of variables declared in a given method.

This is an entirely contrived example. In the real world it might be used as an indicator of how complex a method is. However, you could also use the “Maintenance complexity” or “Cyclomatic Complexity” that comes with CodeRush :)

This theory this metric should involve:

  • Iterating through every node within the AST (Abstract syntax tree) looking for items representing variables.
  • Count these items and pass this count back to the DXCore for rendering by CodeRush

In practice this is a lot simpler than it sounds.

First you’ll need to create a new plugin. Once this is done, you’ll want to add a CodeMetricProvider to the design surface of the plugin. It can be found on the “DXCore: Extensions & Providers” tab of your toolbox and looks like this.CodeMetricProviderOnce dropped on the design surface, we should set a few properties.

ProviderName: ‘VariableCountMetric’
DisplayName: ‘Variable Count’
Description: Counts the variables declared within the member.
MetricGoal: Members
Warning: 10

Then handle the single event ‘GetMetricValue’.

The Theory

Your goal within the GetMetricValue, is to set e.Value based on some measureable quality of e.LanguageElement.

You could do anything here.. random numbers, length of member name, characters in method, characters in method if it were rendered in a different language :P All sorts.

In this case we will examine e.LanguageElement (the method) and calculate the number of variable declarations within it.

The “Warning” property is to give Coderush a value which is considered excessive for this metric.

Simples! :D

The Practice
Ok so how to count variables in a method?
Well the simplest way is…
SomeMethod.AllVariables.Cast(Of Variable).Count

So add this code to you handler and you’re done…
Dim Method As Method = TryCast(e.LanguageElement, Method)
If Method IsNot Nothing Then
      e.Value = Method.AllVariables.Cast(Of Variable).Count
End If

Ta Da…. Seriously go try it out…

If you get this to run successfully, then go have a look at some of the other “All” methods that hang off the method class..

Like AllExpressions, AllFlowBreaks, AllParameters or AllStatements. Similar methods exist on the ‘Type’ class.

Note: Remember to load your plugin via the “plugin manager” if you set it to “Load manually” when you created it (as you should have)

No comments: