Using reflection to ease code maintenance
Currently I am programming an application for performing code analysis on the software that controls the production process. Apart from the parsing of the code, and iterating across a hierarchical representation of the expression tree, all these rules (verifications) have to be executed against all the code.
I could change the code verifier every time I implemented a new rule, but instead I used reflection to do this for me. Every verification that has to be done is represented by a class that implements the right interface. This interface defines the prototype of the method that performs the verification.
interface IActionVerification
{
void Verify(CodeContext context);
}
The context variable contains the complete context of the portion of the code that is being looked at: the current action, step, function block and phase.
When a new code verifier instance is create, it will use reflection to examine the current assembly, and extract all classes that implement this interface.
public CodeVerifier()
{
actionVerifications = new List<IActionVerification>();
var currAssembly = Assembly.GetExecutingAssembly();
foreach(Type t in currAssembly.GetTypes())
{
if (null != t.GetInterface(typeof(IActionVerification).Name))
actionVerifications.Add(
(IActionVerification)
currAssembly.CreateInstance(t.FullName));
}
}
This way, it is very easy to populate the list of all verifications to do. The code verification itself is conceptually as simple as this:
foreach (var verification in actionVerifications)
verification.Verify(context);
Implementing a new verification is the as easy as creating a new class and implementing the interface. After that everything will be done automatically. Ading a new verification is as easy as this:
class ActionExpressionCount : IActionVerification
{
public void Verify(CodeContext context)
{
if (context.Action.ParsedExpression.Count < 1)
ActionExpressionCountInvalid.LogIssue(context);
}
}
Hip hip hooray for the .NET framework!