Hugoware

The product of a web developer with a little too much caffeine

Using Delegates As Parameters

with 2 comments

I’m not sure the community stance on passing around delegates as arguments but personally I love it. I think there is something magical about the way you can provide instructions on how how to do something and then pass it into another method and let it do its job without needing to think about it. It is almost like writing a code template and then filling in the blanks with the specifics of what you need.

Using delegates as arguments can simplify code and in some cases reduce it. This post goes over a sample scenario where you might use delegates as arguments instead of writing multiple functions to perform different tasks.

Simple Resource Loader

Let’s pretend we have a class that is responsible for loading and saving files from an external resource. We could write a class like the one below.


//handles loading resources for the application
public static class ResourceLoader {

    //returns the bytes for a resource
    public static byte[] LoadBytes(string resource) {
        string path = ResourceLoader._GetResourcePath(resource);
        return File.ReadAllBytes(path);
    }

    //returns a xml document resource
    public static XDocument LoadXmlDocument(string resource) {
        string path = ResourceLoader._GetResourcePath(resource);
        return XDocument.Load(path);
    }

    //returns a bitmap resource
    public static Bitmap LoadBitmap(string resource) {
        string path = ResourceLoader._GetResourcePath(resource);
        return Bitmap.FromFile(path) as Bitmap;
    }

    //returns the string text for a resource
    public static string LoadText(string resource) {
        string path = ResourceLoader._GetResourcePath(resource);
        return File.ReadAllText(path);
    }

    //generates a path to a resource
    private static string _GetResourcePath(string file) {
        return Path.Combine(@"c:\path\to\files\", file);
    }

}

Nothing is really wrong with this code. If we need to add a new type to this class then we simply create a new method and plug it in. Additionally, each of the methods could use some sort of exception handling in case the conversion doesn’t go so well. As you can imagine, the more try catch blocks we add, the larger this class starts to get.

However, if you think about it, all of these resources could be handled roughly the same way. They all need a way to convert bytes to whatever type you’re wanting.

Using A Delegate To Fill In The Blank

So instead, lets address this problem using a delegate to handle the conversion of bytes to the type that we need.


//handles loading resources for the application
public static class ResourceLoader {

    //returns the bytes for a resource
    public static T Load<T>(string resource, Func<byte[], T> convert) {

        //find the correct path
        string path = Path.Combine(@"c:\path\to\files\", resource);
        byte[] bytes = File.ReadAllBytes(path);

        //attempt convert the file
        try {
            return convert(bytes);
        }
        //if it fails, forward the error to the caller
        catch (Exception ex) {
            throw new FormatException(
                string.Format(
                    "Could not load resource '{0}' as a type {1}", 
                    resource, typeof(T).Name
                    ), ex);
        }

    }

}

Great — Now we can provide any method we want to format the bytes and then return the type we’re looking for. So for example, instead of calling ResourceHandler.LoadBitmap we can use our new method as shown below.


Bitmap bitmap = ResourceLoader.Load("test.jpg", (bytes) => {
    using (MemoryStream stream = new MemoryStream(bytes)) {
        return Bitmap.FromStream(stream) as Bitmap;
    }
});

Pretty slick, right? …oh, wait… this code is longer and more difficult to use… This can’t be right!

Bringing The Concept Together

Clearly, the example above isn’t improving anything for us. The code is longer and requires that we write the same functionality for reading a resource in multiple places. Even though this code is more flexible, it also requires more work. So instead, lets write some definitions of common conversions as part of our class.


//handles loading resources for the application
public static class ResourceLoader {

    //Load<T>(resource, convert)
    //snip...

    //converts bytes to a bitmap
    public static readonly Func<byte[], Bitmap> AsBitmap = (bytes) => {
        using (MemoryStream stream = new MemoryStream(bytes)) {
            return Bitmap.FromStream(stream) as Bitmap;
        }
    };

    //converts bytes to a xml document
    public static readonly Func<byte[], XDocument> AsXml = (bytes) => {
        using (MemoryStream stream = new MemoryStream(bytes)) {
            using (StreamReader reader = new StreamReader(stream)) {
                return XDocument.Parse(reader.ReadToEnd());
            }
        }
    };

    //converts bytes to a string
    public static readonly Func<byte[], string> AsText = (bytes) => {
        return Encoding.UTF8.GetString(bytes);
    };

    //simply returns the byte array
    public static readonly Func<byte[], byte[]> AsBytes = (bytes) => bytes;

}

Now, instead of needing to manually create a delegate to handle the conversion process we can write code like the example below.

 
//Loads a resource by passing the static delegate that is part of the class we created
Bitmap bitmap = ResourceLoader.Load("test.jpg", ResourceLoader.AsBitmap);
 

By using delegates as an argument we allow our loading function to be flexible enough to accept other methods for performing the conversion (that we can create as we need them) or the common conversion methods that we added as part of the class.

You’ll also notice that we don’t need to declare the generic type we’re wanting to have returned since it can be inferred from the return type of the delegate we pass in! (so cool… to me at least)

Of course, there is about a hundred different ways to can already load resources in .NET but you could apply this same concept many other areas of applications you develop.

How could you use delegates to create “templates” for code?

Advertisements

Written by hugoware

January 13, 2010 at 1:58 am

2 Responses

Subscribe to comments with RSS.

  1. I have a fever and the answer is more delegates. Your explanation of passing a method around as a parameter is a good one, as I think it is a better entry point for OO design for developers. It is a simpler explanation than what we get with most discussions of IoC and Dependency Injection.

    What you’ve discussed is more concrete than the standard phrase “solving complex problems through object composition.” Delegates are very powerful feature, but getting your head around the concept can be daunting for people. You’ve done it simply – pass a method when you need. That leads to further issues of loose coupling, open-closed principle, and code maintainability. Nice job.

    ActiveEngine Sensei

    January 18, 2010 at 7:56 am

    • Interestingly, a growing number of my blog posts are discussions I’m having with people I work with. This was related to an actual project we were working on.

      You are correct that it is very difficult to understand the concept of passing ‘something to do’ instead of ‘something to evaluate’ as an argument. This example isn’t great in the sense that your might tear down all of your resource loading code in favor of this approach, but it is a good way to guide someone new to programming with something that makes sense.

      Too often I find code examples that are super complex and super vague at the same time which inevitably leads to me abandoning learning any more about it. If you can’t get someone to see an applicable use to some code — no matter what kind of time saver it might be in the future — then they probably won’t finish the research to find out if it is worth their time in the end.

      Of course, if a ranking member of the programming community, say @scottgu or @shanselman were to suggest that we learn something then we might want to take note. Otherwise, the concept must be explained clearly and quickly to see the purpose without needing hours of research…

      …however, I’m rambling (not keeping it short) here so I’ll stop… 🙂

      webdev_hb

      January 19, 2010 at 10:31 am


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: