A Day In The Lyf

…the lyf so short, the craft so longe to lerne

Archive for July 2007

Using Higher Order Functions in Windows Forms Applications

My wife is in the middle of a research project comparing diet to the age of reproduction in African house snakes. She has to collect quite a bit of data, and when I finally looked at the spreadsheets she was maintaining, I was ashamed that I had not written something for her earlier.

This was really the first Windows Forms application that I’ve had the opportunity to do in years (my UI’s aren’t very inspiring). However, I have to maintain a couple at work that were primarily written by former colleagues, and I’ve always been a bit dismayed at the enormous amount of duplication that the standard event-driven application generates.

Despite the fact that the application I wrote for my wife was nothing more than a one-off application, one which you don’t expect to have to maintain, I focused on eliminating the duplication I see in the Windows applications at work. The result isn’t something that I would even begin to consider done for a corporate application, but I found the duplication removal techniques worth writing about. The code can be found here.

The biggest gains in removing duplication, and the ones most readers are likely to be least familiar with, are the use of higher order functions. My impression is that most C# developers aren’t very comfortable with higher order functions. Actually, I think that’s probably true for most developers working within mainstream commercially developed (Microsoft, Borland, Sun) languages. They’re simply not emphasized enough.

For example, all the forms had a ListView to display the data. All of them had to define the column header names and the data that goes in each row. It looked something like this:

protected override void AddHeaders()
{
    AddHeader(“Weight”);
    AddHeader(“Length”);
    AddHeader(“HL”);
    AddHeader(“HW”);
}

protected override void AddCells()
{
    AddCell(Weight);
    AddCell(Length);
    AddCell(HeadLength);
    AddCell(HeadWidth);
}

Having the subclass define the column header names and the data that goes in each row didn’t bother me. What did bother me was having to specify the order that the headers and data needed to be shown in two different place. However, while the header names were static, the data would be different for each invocation. The result was to specify the order only once, in an associative array (I used .NET 2.0’s generic Dictionary, which seemed to maintain the order I entered the items). The key would be the column name, and the value would be a function to retrieve the data value.

// The superclass for all Forms…
public class SnakeForm : Form
{
    protected delegate object GetterDelegate(object value);

    private IDictionary associations;

    protected virtual void AddListViewAssociations(
        IDictionary associations)
    {
        throw new NotImplementedException(“Override…”);
    }

    protected virtual IEnumerable ListViewHeaders
    {
        get
        {
            foreach (string header in associations.Keys)
                yield return header;
        }
    }

    protected virtual IEnumerable ListViewValues(object value)
    {
        foreach (GetterDelegate getter in associations.Values)
            yield return getter(value);
    }

    protected virtual void AddCells(object source)
    {
        foreach (object value in ListViewValues(source))
            AddCell(value);
    }

    private void SnakeForm_Load(object sender, EventArgs e)
    {
        associations = new Dictionary();
        AddListViewAssociations(associations);
        AddHeaders();
    }

    private void AddHeaders()
    {
        foreach (string header in ListViewHeaders)
            AddHeader(header);
    }

    private void AddHeader(string name)
    {
        ColumnHeader header = new ColumnHeader();
        header.Text = name;
        lvData.Columns.Add(header);
    }
}

The important things to note are that the subclass is passed, in a template method, a collecting parameter, associations, each entry of which represents a column name along with a way of retrieving the value for a row in that column. The delegate used to retrieve the value can be passed a single state parameter, which is needed by the report forms that need to pass in the source object for each row. Given that information, the superclass can manage most of the work. (AddListViewAssociations would have been abstract, except for the fact that Visual Studio’s designer doesn’t much care for abstract classes.)

For example, here is the information for the measurement form that was first given to show the problem:

protected override void AddListViewAssociations(
    IDictionary associations)
{
    associations.Add(“Weight”, delegate { return Weight; });
    associations.Add(“Length”, delegate { return Length; });
    associations.Add(“HL”, delegate { return HeadLength; });
    associations.Add(“HW”, delegate { return HeadWidth; });
}

One of the benefits of removing the ordering duplication is that the column names now sit beside the functions for retrieving the values, making it easier to understand. Notice that the GetterDelegate definition actually accepts an object parameter. C#’s anonymous delegate syntax lets you ignore unused parameters, making for a somewhat more readable line.

One of the forms shows the information about feedings per snake, and needed that parameter. Below is the entire implementation of the form (aside from the designer-generated code).

// ReportForm is a subclass of SnakeForm
public partial class FeedingBySnakeReport : ReportForm
{
    public FeedingBySnakeReport()
    {
        InitializeComponent();
    }

    protected override void AddListViewAssociations(
        IDictionary associations)
    {
        associations.Add(“Snake”, delegate(object obj)
            { return ((FeedingReportDto)obj).Snake; });
        associations.Add(“Diet”, delegate(object obj)
            { return ((FeedingReportDto)obj).Diet; });
        associations.Add(“Date”, delegate(object obj)
            { return ((FeedingReportDto)obj).Date; });
        associations.Add(“Weight”, delegate(object obj)
            { return ((FeedingReportDto)obj).Weight; });
        associations.Add(“Food Weight”, delegate(object obj)
            { return ((FeedingReportDto)obj).FoodWeight; });
        associations.Add(“Ate?”, delegate(object obj)
            { return ((FeedingReportDto)obj).Ate; });
        associations.Add(“%BM”, delegate(object obj)
            { return ((FeedingReportDto)obj).PercentBodyMass; });
        associations.Add(“Comments”, delegate(object obj)
            { return ((FeedingReportDto)obj).Comments; });
    }

    protected IEnumerable GetReportValues()
    {
        FeedRepository repository = new FeedRepository();
        return repository.FeedingsBySnake(Snake);
    }
}

In case you’re wondering what this form does, it allows you to select a snake, or all snakes, and see the feeding information in the ListView. It also lets you export all the data to a CSV file. Not bad for 30 lines of code.

Another thing that bothered me about all the event handlers was how similar they looked. The workflow was abstracted in the superclass into a HandleEvent method:

protected delegate void EventHandlerDelegate();

protected virtual void HandleEvent(EventHandlerDelegate handler)
{
    Cursor = Cursors.WaitCursor;
    try
    {
        handler();
    }
    catch (Exception ex)
    {
        ShowError(ex.Message);
    }
    finally
    {
        Cursor = Cursors.Default;
    }
}

HandleEvent takes a function that handles the meat of the event handler and wraps it within the code that’s common to all event handlers. Here’s a couple examples:

// In DataEntryForm, an abstract superclass, and subclass of SnakeForm
private void btnSave_Click(object sender, EventArgs)
{
    HandleEvent(delegate
    {
        if (!IsOkToSave())
            return;

        Save();
        AddRow(null);
        FinishListViewUpdate();
        Reset();
    });
}

// In ReportForm, an abstract superclass, and subclass of SnakeForm
private void btnShow_Click(object sender, EventArgs e)
{
    HandleEvent(delegate
    {
        lvData.Items.Clear();

        // GetReportValues() is a template method defined in the subclasses.
        IEnumerable reportValues = GetReportValues();
        foreach (object record in reportValues)
            AddRow(record);
    });
}

Managing the ListView proved to be fertile territory for removing duplication through higher order functions. For example, I used the first row’s data to set the column alignments automatically—if it looked like a number or date, right-align the data; otherwise left-align it.

private void SetAlignments(object record)
{
    int i = 0;

    // A bit hackish, but the report dtos currently provide strings only…
    foreach (object value in ListViewValues(record))
    {
        if (IsNumber(value) || IsDate(value))
            lvData.Columns[i].TextAlign = HorizontalAlignment.Right;
        else
            lvData.Columns[i].TextAlign = HorizontalAlignment.Left;

        i += 1;
    }
}

private bool IsNumber(object value)
{
    try
    {
        double.Parse(value.ToString().Replace(”%”, ””));
        return true;
    }
    catch
    {
        return false;
    }
}

private bool IsDate(object value)
{
    try
    {
        DateTime.Parse(value.ToString());
        return true;
    }
    catch
    {
        return false;
    }
}

Look how alike IsNumber and IsDate look. We can simplify:

private delegate void ParseDelegate(string text);

private bool IsNumber(object value)
{
    return CanParse(value, delegate(string text)
        { double.Parse(text.Replace(”%”, ””)); });
}

private bool IsDate(object value)
{
    return CanParse(value, delegate(string text) { DateTime.Parse(text); });
}

private bool CanParse(object value, ParseDelegate parser)
{
    try
    {
        parser(value.ToString());
        return true;
    }
    catch
    {
        return false;
    }
}

I used a similar trick to auto-size the column widths in the ListView based on the width of the largest item. Here’s the refactored code:

private delegate string GetTextDelegate(int index);

private void AutoSizeListView()
{
    int[] widths = new int[lvData.Columns.Count];
    FillSizes(widths, delegate(int i) { return lvData.Columns[i].Text; });

    foreach (ListViewItem item in lvData.Items)
    {
        FillSizes(widths, delegate(int i) { return item.SubItems[i].Text; });
    }

    for (int i = 0; i < lvData.Columns.Count; i++)
    {
        if (!IsHidden(lvData.Columns[i]))
        {
            lvData.Columns[i].Width = widths[i] + 12;
        }
    }
}

private void FillSizes(int[] widths, GetTextDelegate text)
{
    using (Graphics graphics = CreateGraphics())
    {
        for (int i = 0; i < lvData.Columns.Count; i++)
        {
            SizeF size = graphics.MeasureString(text(i), lvData.Font);
            if (size.Width > widths[i])
                widths[i] = (int)size.Width;
        }
    }
}

private bool IsHidden(ColumnHeader header)
{
    return header.Width == 0;
}

If this were a more long-lived application, I really should have bit the bullet and created my own ListView subclass. The methods above reek of Feature Envy.

Being able to treat functions as first-class objects is extremely useful. For some reason, it doesn’t get the attention it deserves in most development books. And it’s often somewhat obscured by intimidating sounding names like “lambda expressions” thanks to its roots in lambda calculus. However, much of what I was able to do in this application was possible only because I was able treat functions as data and pass them as parameters. And it was helped by the fact that I didn’t have to explicitly define each function as a method; I could create them anonymously like any other data object (although C#’s anonymous delegate syntax is somewhat obscured by the static typing).

Written by Brandon Byars

July 17, 2007 at 12:22 am

Posted in .NET, Design

Tagged with

Follow

Get every new post delivered to your Inbox.