Cottleston Pie

Fernando Felman’s thoughts on software development

Using Generics to code type-free helpers

Posted by Fernando Felman on March 2, 2007

The other day I received a small WinForm application to review. The application uses many forms, each designed for a single-specific task. I noticed that in the main form, the developer duplicated the following code snipped to initiate various forms:

if ((this.frmUtil1 == null) || this.frmUtil1.IsDisposed)
{
    this.frmUtil1 = new Forms.Util1();
}
this.ShowForm(this.frmUtil1);

if ((this.frmUtil2 == null) || this.frmUtil2.IsDisposed)
{
    this.frmUtil2 = new Forms.Util2();
}
this.ShowForm(this.frmUtil2);

One of the best practices I found is that if you’re duplicating a code section, it’s a good indication of a shared functionality that can be encapsulated. We’d like to have a service that will receive an object representing the WinForm and handle it by properly initiating the form when required:

public void ShowForm(Form sourceForm, Form reusableForm);

In .Net 1.1 we must go through reflection in order to create an object of the correct class dynamically, but in .Net 2.0 we’ve got Generics to facilitate things:

static class FormHelper<T>
    where T : Form, new()
{
    public static void ShowForm
        (Form sourceForm, ref T reusableForm)
    {
        if (reusableForm == null || reusableForm.IsDisposed)
        {
            reusableForm = new T();
        }
        sourceForm.Show(reusableForm);
    }
}

Notice the usage of the new constraint after the description of the type T: this tells the compiler that the type T supports a default public constructor and so we can easily create a new object of the T class using new T();

To use the service you’d pass the type of the forms and both forms varibales:

FormHelper<Froms.Util1>.ShowForm(this, ref this.frmUtil1);

This would both initiate this.frmUtil1 with a new instalse of Froms.Util1 when needed and also show the form.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: