Reshef’s tip of the day

.net development tips

Posts Tagged ‘reflection’

DynamicMethod full example

Tuesday, December 18th, 2007

My last post described how to generate a dynamic method for object instantiation that its type is not known at compilation time.

I felt that the code snippets in that post were too technical and it was hard to understand how and when to use it in the real world. Therefore I created a small sample application that shows how and when it can be used.

The application is a small rule engine that gets a rule definitions file about a user’s credit, parses the rules, generates C# code and compiles the code on runtime. The rule engine is then instantiated by using a dynamic method.

The file UserCreditRules.rules contains the definitions of the rules and the dynamic method is generated in the file RulesFactory.cs by the method GenerateFactoryMethod(…).

The sample application is here.

Reflection and performance: DynamicMethod

Monday, December 17th, 2007

Reflection has a performance price, however, there are times that it just can’t be avoided, like when creating a new instance of a type generated and compiled at runtime. Since the type does not exist when compiling the code, it can’t be referenced and therefore can’t be instantiated by:

BaseType instance = new GeneratedType();

where BaseType is the a type that GeneratedType inherits from.

So how to instantiate?

After generating the assembly, we have a reference to that assembly. The most naive and simple way is to call:

BaseType instance = (BaseType)generatedAssembly.
    CreateInstance("GeneratedType");

But unfortunately this is also the worst way performance-wise, since on runtime first it looks for the name of the generated type through all the types in the assembly, then it looks for the appropriate constructor and then it instantiates the object. It can be optimized by caching the ConstructorInfo of the  type and then calling it, which highly optimizes the instantiation time. There are other ways to achieve this goal but I am not going to go into it. For a thorough article and analysis take a look here (the source code is here).

In order to get the best performance, we can use the DynamicMethod class which generates IL code at runtime and creates a method out of it. This is done like this:

Type generatedType = CompilerSimulator.Compile().
    GetType("generated type name");

DynamicMethod dm =
    new DynamicMethod("GeneratedCtor", generatedType,
        Type.EmptyTypes, typeof(ContainingType).Module, true);

ILGenerator ilgen = dm.GetILGenerator();
ilgen.Emit(OpCodes.Nop);
ilgen.Emit(OpCodes.Newobj,
    generatedType.GetConstructor(Type.EmptyTypes));
ilgen.Emit(OpCodes.Ret);

GeneratedTypeFactoryMethod factoryMethod =
    (GeneratedTypeFactoryMethod)dm.CreateDelegate(
    typeof(GeneratedTypeFactoryMethod));

The GeneratedTypeFactoryMethod is a delegate:

delegate BaseType GeneratedTypeFactoryMethod();

Now, our code can return the generated method as delegate that will be called to to create a new instance of the generated type. By tests that I did I got results similar to direct instantiation (after setting up the factory delegate - but this happens only once).

Since writing IL code is not much fun, you can use a project named RunSharp that wraps IL emitting with a high-level interface.

Null object pattern

Monday, December 10th, 2007

There is a lot written about the null object pattern in the web, but it took me quite some time to find an example that I could relate to for null object.

Take a scenario where we have a email application with a message class:

public class Message
{
    private string m_recipient;
    private MailAccount m_account;

    public string Recipient
    {
        get { return m_recipient; }
        set { m_recipient = value; }
    }

    public MailAccount Account
    {
        get { return m_account; }
        set { m_account = value; }
    }
}

Lets say that we would like to view the massage pane window (pretty common requirement for a mail client), we will have to test the the Recipient and Account member for null value before accessing them.

Side effects when testing for null values is that we add code to the presentation logic which can possibly look like that:

void ShowMessage(Message m)
{
    string recipientDisplay = m.Recipient ?? String.Empty;

    string accountDisplay = m.Account ?? "NotSet";
    if(m.Account == null)
    {
        accountDisplay = "NotSet";
    }
    else
    {
        accountDisplay = m.Account.Name;
    }
    txtRecipient = recipientDisplay;
    txtAccountName = accountDisplay;
}

This is a lot of code just for displaying two fields. We should also remember that a developer can possibly forget to test for null values and therefore to get a null reference exception.

The null object attempts to help here. One possible implementation is by implementing the Message class like this:

public class Message
{
    // String.Empty is the null object for recipient
    private string m_recipient = String.Empty;

    // Set the "NotSet" account as the default value
    private MailAccount m_account = MailAccount.NotSet;

    public string Recipient
    {
        get { return m_recipient; }
        set { m_recipient = value; }
    }

    public MailAccount Account
    {
        get { return m_account; }
        set { m_account = value; }
    }
}

Where the MailAccount class is implemented like that:

public class MailAccount
{
    public static readonly MailAccount NotSet =
        new MailAccount("Not set", "0.0.0.0", false);

    private string m_name;
    private string m_serverAddress;
    private bool m_isSsl;

    public MailAccount(
        string name, string serverAddress, bool isSsl)
    {
        //parameter validation…
        m_name = name;
        m_serverAddress = serverAddress;
        m_isSsl = isSsl;
    }

    public string Name
    {
        get { return m_name; }
    }

    public string ServerAddress
    {
        get { return m_serverAddress; }
    }

    public bool IsSsl
    {
        get { return m_isSsl; }
    }
}

Here you can see that there is a static property called NotSet which is the null object. The field m_account is set by default to the NotSet account. The field m_recipient is set to String.Empty which also serves as a null object.

void ShowMessage(Message m)
{
    txtRecipient = m.Recipient;
    txtAccountName = m.Account.Name;
}

Because we know that both Recipient and Account are not initialized to null, we can skip the null checking and thus we get much simpler and more readable code.

One thing that I like, is that now when the account is a null object (account not set), the default values will be displayed ("Not set" and address "0.0.0.0").

A small problem with this kind of implementation is that the properties of the NotSet instance can be changed by reflection but the next part can solve that.

Another way to implement a null object is by subclassing or implementing an base interface. Based on the previous example, lets add an interface that represents an account:

public interface IMailAccount
{
    bool IsSsl { get; }
    string Name { get; }
    string ServerAddress { get; }
}

The MailAccount class will now look like that:

public class MailAccount : IMailAccount
{
    private string m_name;
    private string m_serverAddress;
    private bool m_isSsl;

    public MailAccount
        (string name, string serverAddress, bool isSsl)
    {
        //parameter validation…
        m_name = name;
        m_serverAddress = serverAddress;
        m_isSsl = isSsl;
    }

    public string Name
    {
        get { return m_name; }
    }

    public string ServerAddress
    {
        get { return m_serverAddress; }
    }

    public bool IsSsl
    {
        get { return m_isSsl; }
    }
}

Pay attention that the class now implements the IMailAccount interface and it does not contain the null object static field. The null object is implemented like this:

public class NullMailAccount : IMailAccount
{
    public NullMailAccount() {}

    public bool IsSsl
    {
        get { return false; }
    }

    public string Name
    {
        get { return "NotSet"; }
    }

    public string ServerAddress
    {
        get { return "0.0.0.0"; }
    }
}

and then the Message class will look like like this:

public class Message
{
    private static readonly IMailAccount
        MailAccountNullObject = new NullMailAccount();

    // String.Empty is the null object for recipient
    private string m_recipient = String.Empty;

    // Set the mail account null object
    private IMailAccount m_account = MailAccountNullObject;
    …

The usage of the Message class remains the same.

This implementation is also safe for reflection since the NullMailAccount class has no fields to change and in the class message, the field MailAccountNullObject is a readonly field which can’t be set by reflection.

So to conclude, the points that I liked the most about the null object pattern are:

1) Reduces significantly the chances of getting a null reference exception.

2) Defines a common behavior for fields that were not set yet such as the case of a common value to display.

Jajah is the VoIP player that brought you web-activated telephony.