Thursday, June 25, 2009

The ElementEnumerable Class

In our previous tutorial we showed how to use Methods like AllVariables and AllExpressions to extract information from some code in order to furnish the Code Metric subsystem of Coderush with additional Metric possibilities.

But what happens if you want to gather something that is not catered to explicitly? Perhaps you’d like to write an ExtremeMetric which counts Try..Catch information?

Let me introduce you to my good friend ‘ElementEnumerable’


ElementEnumerable is exactly what it sounds like. It a class which is used for Enumerating Elements. It’s constructor takes a scope element, a Type filter and an option to recurs or not.

It implements IEnumerable and when used as an Enumerator, it will enumerate across the scope you handed it, stopping to pass out anything which matches what you asked it to filter.

We can create a MethodEnumerable for the current class thus…
e.Value = New ElementEnumerable(SomeClass, GetType(Method)).Cast(Of Method).Count

Our Variable Enumerator will be only slightly more complicated..

e.Value = New ElementEnumerable(SomeMethod, GetType(Variable), True).Cast(Of Variable).Count

The reason for the True param at the end is to allow The ElementEnumerable to recurse inside things like if statements in order to find variables declared deeper that the top level of the method in question.

In our previous example of a MethodEnumerable, we can safely assume that the methods we would like to find are all immediate children of the start point. If we had not made this specification, we could well have returned methods belonging to a nested class.

So if we wanted to count Try Statements, we could use….

e.Value = New ElementEnumerable(Method, GetType([Try]), True).Cast(Of [Try]).Count

…and of course you can do all kinds of calculations before you actually set this value.

So why don’t you go nuts and invent your own metric. Any questions? Just let me know :)

No comments: