Adapting Method Signatures…Functional Style

26. March 2010 00:09

Over the last year or so, I’ve become increasingly interested in functional programming.  There is just something elegant and sexy about the ways in which it can be applied.  In an effort to find more opportunities to apply a functional approach, I’ve started using delegates a lot more in my code.  I am gradually starting to see patterns emerge where the delegates offer a cleaner solution.  Perhaps, it would be more accurate to say combining delegates.

I recently had what I thought would be a practical example to share.  Rather than getting into a long tangent about the context, I’m going to get to the point and keep the example as short as possible.  Hopefully, you will still see the benefit and the point.

I was working on some code to facilitate simple SELECT queries that automatically get mapped into an instance of a specified type.  Here is a simplified version of the relevant code. 

public class Query
{
    readonly string sql;
    readonly Func<IDataReader, object> load_results_from;

    public Query(string sql, Func<IDataReader, object> load_results_from)
    {
        this.sql = sql;
        this.load_results_from = load_results_from;
    }

    public object run_against(IDatabase database)
    {
        using (var reader = database.execute_reader(sql))
            return load_results_from(reader);
    }
}

 

As you can see, there is nothing really glamorous about this code.  It allows the consumer to run a query against some database and map the results into an object.  The portion of interest for this post is how the result set gets transformed into an instance of a type with all of its properties automatically set. 

For the signature of the delegate responsible for loading the results, I’ve chosen for it to simply take an IDataReader and return some object.  This allows the consumer instantiating the class to have a great deal of flexibility for changing the behavior of loading the result set.  It is really nothing more than a strategy.  I could have declared an IResultLoadingStrategy to do the same thing, but this would require the consumer to create a class to provide another concrete implementation when they want to use a different strategy.  With this approach, the consumer only needs to provide a method, which could even be a simple lambda expression.

In most cases, I want to use AutoMapper and let it automatically handle the transformation from an IDataReader into the specified result type.  However, I need to give AutoMapper an additional argument.  It needs to know the Type of the object to return in order to perform the mapping procedure.  Based on the current signature, the Query class uses a delegate that accepts IDataReader.  Now, we could change the delegate to also accept a Type argument, but it seems unnecessary to me.  If a consumer is going to provide a custom method for loading results, I’m going to assume that the consumer already knows the type to be returned and will handle it accordingly in the supplied delegate.  So, why should I make them pass the type if they aren’t going to use it?  [Yes, you could argue the other way as well, but this is my example!]

Instead of changing the signature of the delegate to meet the needs of AutoMapper, we really need a way to adapt the AutoMapper signature to the signature required by the Query class.  If we had used an interface to define the signature of the load strategy, we could use the traditional adapter pattern.  However, it would require creating even more classes when all we really want is a function. 

 

Let’s see how a functional programming approach could achieve the same results as the traditional adapter pattern.

We basically need the following line of code for AutoMapper to perform the transformation (assuming a mapping has already been created):

return Mapper.Map(reader, typeof(IDataReader), result_type); 

 

So, we need to pass IDataReader and the Type of the result in order to get back the mapped instance.  However, the Query class requires a function that only accepts IDataReader and returns an object.  Recall the delegate as shown below:

Func<IDataReader, object> 

 

Basically, the problem is we need a way to adapt the necessary signature for AutoMapper

Func<IDataReader, Type, object>

to the signature needed by Query

Func<IDataReader, object>

 

If we put on our functional programming hat, a functional solution starts to seem obvious.  All we really need is a function that returns another function.  Something with a signature like this:

Func<Type, Func<IDataReader, object>>

 

How could that possibly work?  Closures to the rescue! 

public class MyAdapters
{
    public static Func<Type, Func<IDataReader, object>> auto_map = (result_type) =>
    {
        Func<IDataReader, object> load_result = (reader) =>
        {
            return Mapper.Map(reader, typeof(IDataReader), result_type);
        };

        return load_result;
    };
}

 

This does exactly what we need.  When auto_map is invoked, it is given the Type of the result that AutoMapper requires for the transformation.  The value of result_type is captured within a closure that corresponds to the signature required by the Query class.

In other words, you could create an instance of the Query class that uses AutoMapper by doing the following:

var query = new Query("SELECT * FROM ViewModel", MyAdapters.auto_map(typeof(ViewModel)));

 

This is a big part of what functional programming is all about.  Functions can return other functions.  When you start to look at your applications in this way, there are lots of interesting possibilities that arise from combining functions in many different ways.  Hopefully, this example has made some [minor] sense and you can get an idea of what’s possible.

But, wait a minute!  There is one last thing that still bothers me a bit.  Our functional solution may be “elegant”, but it seemed a bit ugly and difficult to read…especially with the nested function declaration with generics.  Wouldn’t it be nice to clean that up a bit.  Thanks to the C# 3.0, we can reduce the code quite a bit.  Actually, just one dense line:

public class MyAdapters
{
    public static Func<Type, Func<IDataReader, object>> auto_map = 
        (result_type) => 
        (reader) => Mapper.Map(reader, typeof(IDataReader), result_type);
}

 

That is certainly better, but I’m still not crazy about those ugliness of a nested Func<>.  Fortunately, .NET only cares that the underlying signatures match for delegates.  So, we could declare our own delegate with the same signature that has a more meaningful name.

public delegate object LoadQueryResultBehavior(IDataReader reader);
public delegate LoadQueryResultBehavior AutoMapQueryResult(Type destination_type);

public class MyAdapters
{
    public static AutoMapQueryResult auto_map = 
        (result_type) => 
        (reader) => Mapper.Map(reader, typeof (IDataReader), result_type);
}

 

Looking much better!  We could also change the Query implementation to use our custom delegate as well, but it still maintains the same semantics.

public class Query
{
    readonly string sql;
    readonly LoadQueryResultBehavior load_results_from;

    public Query(string sql, LoadQueryResultBehavior load_results_from)
    {
        this.sql = sql;
        this.load_results_from = load_results_from;
    }

    public object run_against(IDatabase database)
    {
        using (var reader = database.execute_reader(sql))
            return load_results_from(reader);
    }
}

 

Mmm…tasty!

Moving my blog to GoDaddy

11. February 2010 18:06

The short story…

I’ve decided to move my blog back over to a shared hosting account with GoDaddy hosting.  If you notice any issues (strange errors, broken links, missing images, etc), please let me know.  It will take a few days for the name server changes to propagate, but I’ve also updated my old host’s DNS to point to the IP address of my site on the GoDaddy server.  So, I would expect any issues to have already been noticed, but you never know.

 

The back story of the change for those that care…

For almost four years, my blog has been hosted at aspnix on one of their Virtual Private Server plans.  Ironically, I started out with my blog hosted on a GoDaddy shared hosting account, but I wanted to setup Community Server and had a lot of trouble getting it to work in their shared environment.  After a while, I finally decided to move elsewhere.  I stumbled onto aspnix and noticed they had very affordable VPS plans.  At the time, it was more than I needed, but I thought a VPS would be a good playground in the cloud for some ideas I wanted to try.  So, I pulled the trigger and migrated my blog to Community Server hosted on a VPS at aspnix.

The first few months were very painful and I almost moved again.  During early 2006, aspnix experienced some growing pains.  There was a good deal of sporadic downtime for a few months, performance issues on SQL Server, and their email infrastructure was practically unreliable.  Fortunately, I toughed it out.  Within a few months, the situation dramatically improved.  Although their email infrastructure continued to be an issue, I setup Google Apps for my domain and starting using the Gmail infrastructure for my email.  After that transition, I never had any more problems and remain a satisfied customer to this day.

So, if I am such a happy customer, why am I leaving aspnix?  At this point, I don’t need a VPS.  It is overkill for my situation.  After a relatively recent restructuring of their fees, I am now paying $57 per month (which is quite a bit more than I was originally paying).  While I consider it to be a good value for what I am getting, I could be getting by with a simple shared hosting account for less than $7 per month.  That is $600 a year back in my pocket just for changing hosts.

If I was happy with aspnix, why not use their shared hosting account?  My domain is registered with GoDaddy and there are some minor benefits to having my site hosted there as well since there is some integration between the domain registration and hosting.  While it may seem like a pitiful excuse, it is one less password for me to remember by having all of it with one company. 

GoDaddy has also changed quite a bit since I last used their services.  You can use a SQL Server database that is publicly accessible.  Previously, all of their databases were not exposed to the internet.  You had to go through their clunky tool to make changes, but it isn’t an issue anymore.  I’ve also moved away from Community Server to BlogEngine.NET, which seems to run smoothly in their shared hosting environment.

 

At any rate, I can still happily recommend aspnix for Virtual Private Server hosting.  Their prices are quite reasonable for what you get.  Actually, it is difficult to find anyone that is cheaper or even close to their range.  If you need a VPS, they are certainly worth a look, but I am still hesitant to recommend using their email infrastructure. 

Resharper Live Templates for WCF Data Contracts

30. January 2010 12:31

If you find yourself doing much WCF development, you are probably familiar with how tedious it can be to create all of the data contracts involved with your service.  To be specific, data contracts necessitate a lot of writing attributes.  Granted, it is now possible to use POCO objects and allow the WCF runtime to infer most of the data contract information from the public members of the given class.  However, I still prefer to be explicit and create the attributes.  On my current project, we also have some custom tooling that relies on the attributes.

Rather than handwriting all of the attributes, Resharper can save you quite a bit of time by leveraging the Live Template feature that it provides.  If you aren’t familiar with Live Templates, they work similarly to snippets in Visual Studio, but it has a lot more power.  On a current project, we are using a generic message dispatching pattern with WCF.  With this approach, there are only a few services in the entire system, but there are *lots* of data contracts.  In order to save some time, I created some Resharper Live Templates that I thought I would share in case others find them to be useful.

First, we start out by writing a class that we want to use as a data contract.

public class Address
{
    public string line1 { get; set; }
    public string line2 { get; set; }
    public string city { get; set; }
    public string state { get; set;}
    public string zip_code { get; set;}
}

Keep in mind that Visual Studio provides a default snippet for quickly creating automatic properties.  Rather than typing the entire information by hand, you can simply type “prop” and press either TAB or ENTER.  The snippet will generate most of the property for you and allow you to quickly fill in the name and type.

With the live templates, we can quickly annotate the class and properties to enable data contracts.  Start by positioning your cursor on the line above the class declaration and type “dc” then hit TAB.

dctemplate_before

The live template generates the DataContract attribute.  By default, it uses the same name as the class for the Name parameter. 

dctemplate_after

To generate the data members, you follow a similar process.  Position your cursor above the property you would like to annotate and type “dm” then hit TAB.

dmtemplate_before

The live template generates the DataMember attribute.  By default, it uses the name of the property as the the value of the Name parameter in the attribute.

dmtemplate_after

By only pressing a few keys, you can quickly annotate the entire class:

[DataContract(
    Name = "Address",
    Namespace = "http://JeffBarnes.Samples")]
public class Address
{
    [DataMember(Name = "line1", IsRequired = true)]
    public string line1 { get; set; }

    [DataMember(Name = "line2", IsRequired = true)]
    public string line2 { get; set; }

    [DataMember(Name = "city", IsRequired = true)]
    public string city { get; set; }

    [DataMember(Name = "state", IsRequired = true)]
    public string state { get; set; }

    [DataMember(Name = "zip_code", IsRequired = true)]
    public string zip_code { get; set; }
}

 

This can save you quite a bit of typing and it is really only a teaser of the capabilities provided by the Resharper template engine.  If you want to give them a try, you download these two templates here.

To install them, go into the Resharper menu of Visual Studio and select the Live Templates menu item.  This will open the live templates window.  Simply click on the Import button and browse to the xml file containing the templates.  After you have loaded the files, you should be able to start using them in Visual Studio as previously outlined.

About My Resharper Talk At AL Code Camp

24. January 2010 14:55

Yesterday, the eighth Alabama Code Camp was held in Mobile, AL.  I delivered three presentations at the event: an introduction to the SOLID principles, a talk on dependency injection and IoC Containers, and an overview of Resharper.  Based on some discussions after the event, I wanted to clarify a few things regarding my presentation about Resharper.

Apparently, I didn’t give enough thought to how the presentation could be perceived or interpreted by others.  Given the code camp series are free community events, it may seem a bit “shady” to have an entire session that promotes a commercial product.  However, it wasn’t my intent to try and sell licenses for JetBrains.  To be perfectly clear, I certainly don’t get anything out of the sale of licenses.  I was not sponsored, endorsed, or otherwise paid by JetBrains to deliver the presentation.  Apart from a free license for the product that I received for being a Microsoft MVP (and is offered to all MVPs), I have never “received” anything from JetBrains.

My only goal with the talk was to really demonstrate how developers can be much more efficient within Visual Studio via productivity and refactoring add-ins.  Since I prefer and really know how to use Resharper, it was the one that was highlighted in the presentation.  To be completely fair, I also pointed out that DevExpress offers CodeRush and Refactor! Pro.  I specifically told the audience that if they don’t already have a preference then it would be prudent to evaluate both products and determine which they like best.  Had I known that Telerik was now offering JustCode, I would have also recommended everyone to evaluate it as well…which brings me to my next point.

Unfortunately, I had never even heard of their product until later in the day when I was talking with Chris Eargle (another presenter and Microsoft MVP).  Chris came down and delivered a couple of talks.  One of them was entitled C# Ninjitsu and it highlighted some of the features in JustCode, which is now in beta.  Coincidentally, my presentation was called “Code Like a Ninja: An Introduction to Resharper”.  Telerik seems to have embraced a “ninja theme” for some of their products.  As such, it may seem a bit deliberate that i chose a “ninja theme” for my presentation in an effort to get in a dig against Telerik.  However, I assure you this is purely coincidental.

Back in June 2009, I gave the same Resharper presentation to the Birmingham .NET User Group with the same title for the presentation.  I just wanted a catchy title to make people more interested.  So, I first used the “Code Like a Ninja” title well before JustCode was ever unveiled.

At any rate, I just wanted to set the record straight from my perspective.  For what it is worth, I apologize to anyone that took offense.  In the future, I’m going to refrain from giving any talks that could be perceived to endorse a particular product at the code camp and INETA user group venues, but I still consider it to be fair game for internal company user groups.

Alabama Code Camp – Jan 23

13. January 2010 14:04

I wanted to post a reminder that the next Alabama Code Camp will be held next Saturday (Jan 23) in Mobile, AL at the University of South Alabama.  This will be a great opportunity to network with other developers around the region, learn about aspects of .NET and peripheral technologies with which you are not familiar, and have an opportunity to pick the brains of other developers related to issues you have been facing.

You can get additional information at http://www.alabamacodecamp.com.  And…don’t forget to register.  I hope to see you there.  Feel free to look me up.  I’m always happy to sit around and talk about software development.

As of right now, I will be presenting two sessions (with additional sessions on stand-by in the event of a cancellation).  Here are the abstracts:


Writing SOLID Code: An Overview of the SOLID Principles

SOLID is an acronym that represents five crucial principles of class design in object oriented development.  The terms were originally coined by Robert Martin (aka Uncle Bob) in the 1990s.  Although these concepts are certainly now new, many developers in the mainstream .NET community are unaware they exist.  In this session, we will examine the significance of these principles as well as some practical examples of how to apply them in your applications.  Come and learn how pragmatically embracing these concepts can make a significant difference in the quality and flexibility of your code.


Why You Should Care About Dependency Injection

Over the last year or two, .NET developers have begun to hear more about terms such as Inversion of Control, Dependency Injection, and IoC Containers.  However, there are still many developers that don’t have any exposure to the concepts or possess a practical understanding of how/when to apply them.  Are you curious what these terms mean, why they are important, and how to apply them?  Please join me for a practical and interactive discussion about how you can greatly reduce the coupling of your code and increase the flexibility of your application by leveraging these concepts.  The Unity IoC Container will be used as a reference for this presentation, but the concepts are applicable to your container of choice.


Write Code Like a Ninja: An Introduction to Resharper

Have you ever been frustrated with Visual Studio?  Do you ever find yourself thinking there must be a faster way to perform a given task, especially those that you do over and over again?  Wouldn't it be nice if there was some shortcut to automate these repetitive tasks such as refactoring?  Fortunately, there is an answer to a lot of these questions.  Resharper is a commercial add-in for Visual Studio that is developed by JetBrains.  Come and see how this inexpensive product can dramatically increase your productivity to help you write code like .NET ninja.  We will go through a comprehensive overview of the major functionality that Resharper 5.0 has to offer as well as a few tidbits of hidden features within Visual Studio.

Professional Resolutions for 2010

6. January 2010 10:19

I feel compelled to write the obligatory New Years Resolutions post.  Honestly, I doubt anyone really cares about my resolutions other than me.  However, it helps with holding myself accountable when I state them publicly.  While I do have some personal resolutions as well, I’m going to keep this focused on professional issues as I attempt to keep personal items out of my technical blog. 

In previous years, I had a tendency to make unrealistic resolutions that I would never meet.  I feel as though it is important to set resolutions that will cause you to stretch yourself, but they shouldn’t be completely unattainable to the point you are setting yourself up for failure.  With that in mind, here are my professional resolutions for 2010:

  • Write at least 50 quality blog posts with technical content.  Rather than setting some goal to blog x number of times a week, I’m shooting for a cumulative goal by end of the year.  I’m also specifying the context.  Posting about events and such doesn’t count.  I want to do a better job of writing technical content…even if it is only for myself.
  • Make at least 5 OSS contributions.  Over the last couple of years, I’ve taken a much greater interest in OSS.  For the most part, this has been limited to using various OSS projects and studying the code.  Going forward, I would like to ease into steadily making contributions.  Next year, I hope to get very involved in a project or two, but I have existing commitments through the end of 2010 that will limit my availability to do so.
  • Write at least 3 articles for Code Project.  It has been nearly two years since I wrote my WCF article on callbacks.  Although it has been relatively well received, I haven’t done the best job of answering questions.  I also have dramatically changed my approach to using WCF during that time.  I want to write a few articles this year (not necessarily related to WCF) and try to provide responses for those with questions.
  • Deliver at least 15 presentations for community events.  I usually do 8 to 10 in a year anyway, but I want to push myself a bit harder this year.  Furthermore, I want to use these presentations as an opportunity to evangelize development principles that have become important to me.  Over the last couple of years, I started my journey into the world of ALT.NET.  It has made a fundamental impact on my approach to software development.  Although I was initially very skeptical, I have come to embrace many of the ALT.NET values.  I want to use these presentations as opportunities to share my perspective.  I don’t expect everyone to agree with me, but I hope to persuade some people to at least consider other alternatives by effectively demonstrating how these alternatives can be useful. 
  • Write a Ruby on Rails web application (at least a simple one).  I want to get more familiar with Ruby…at least enough so that I can have quality conversations with other developers about it.  We are currently using Ruby for a lot of our build scripts, but I would like to be more comfortable with the language so that I can apply it in various ways.
  • Become proficient in F# (and functional programming in general).  F# is a very intriguing language.  As I start to ease more and more into the world of functional programming, it has opened a whole new way of thinking about how to solve certain types of problems.  I want to get better acquainted with the language and understand how it can be applied.
  • Gain a solid understanding of the new toys added in NET 4.0 since it will be officially released this year.  I’ve already played around with it some in the betas, but I need to really dig into some areas.  The new support for parallel programming is of particular interest to me.  I want to acquire a deep understanding of what it can do and how it works.

Those are quite a few goals, but I feel none of them are unattainable.  As intended, they should force me to stretch myself a bit, but I feel as though I can pull them off.  We will see how well I did in a year from now.

Presentation Materials from HUNTUG

12. November 2009 22:54

I have uploaded the materials from my dependency injection presentation at the Huntsville New Technology User Group.  You can download the zip file that contains both the slides and code here.

Once again, I would like to thank everyone that attended.  This was one of my more memorable sessions in recent history.  The interactive discussions were quite enjoyable.  I love being challenged on my points as well as having people share their differing perspectives on the topic at hand.  Overall, I feel as though many pragmatic opinions were revealed during the course of the evening.

If you have any questions about the material, feel free to ping me.

Next Alabama Code Camp – Jan 23, 2010

23. October 2009 17:46

The next Alabama Code Camp has been scheduled for Saturday, January 23, 2010 in Mobile, AL at the University of South Alabama campus. 

For those of you that aren’t familiar with code camp, it is essentially an all-day geekfest that provides a free training and networking opportunity.  It is facilitated by and for developers.  Typically, the covered technologies in the Microsoft .NET realm, but this certainly not a requirement.  There are usually six to seven 1-hour sessions that run concurrently throughout the day (9 to 5’ish).  Topics range from ASP.NET to SQL Server to C# and just about anything in between.  So, there should be something to interest just about everyone.

One of the primary goals of the code camp is to encourage first time speakers that would like to share knowledge about a topic they find interesting.  So, if you would be interested in speaking (or know someone that would be), the call for speakers is officially open.  Visit the website and you will find a document to download that covers the process of submitting a session for consideration.

This will be the 8th code camp in Alabama and I’ve never been to one where I didn’t learn something new…if not from a session at least via conversing with other developers.  It really is a good time.  If you can’t make it to Mobile, the event will be back to Birmingham later in 2010.

Here is the website:  http://www.alabamacodecamp.com  It runs on Silverlight, so it may require a download if you don’t have it installed.

I hope to see you there.

Presenting for Huntsville User Group – Tue Nov 10

8. October 2009 11:03

I’ll be giving my “Why You Should Care About Dependency Injection” talk for the Huntsville New Technology Users Group on Tuesday, November 10th.  If you will be in the area or know someone that is interested, please pass the word along.

 

Here is the abstract:

 

Why You Should Care About Dependency Injection

Buzzwords such as Inversion of Control, Dependency Injection, and containers have become increasingly popular in the world of .NET development. However, many developers are still wondering what’s the big deal? Are you curious what these terms actually mean? Would you like to know why the concepts are important as well as how and when to apply them? If so, please join me for this practical and interactive discussion about how you can greatly reduce the coupling of your application by leveraging these concepts.  The Unity IoC Container will be used as a reference for this presentation, but the concepts are applicable to your container of choice.

Dependency Injection Presentation Material

10. September 2009 15:43

Although it took me a bit longer than I expected, I have finally posted the slides and source code from my recent presentation for the Birmingham .NET User Group.  I would like to thank all of you that attended.  If you have any questions about the material, feel free to ping me.

You can download the material here.

About Me

I'm a passionate software developer and advocate of the Microsoft .NET platform.  In my opinion, software development is a craft that necessitates a conscious effort to continually improve your skills rather than falling into the trap of complacency.  I was also awarded as a Microsoft MVP in Connected Systems in 2008, 2009, and 2010.


Can’t code withoutThe best C# & VB.NET refactoring plugin for Visual Studio
Follow jeff_barnes on Twitter

View Jeff Barnes's profile on LinkedIn

 

Shared Items

Disclaimer

Anything you read or see on this site is solely based on my own thoughts.  The material on this site does not necessarily reflect the views of my employer or anyone else.  In other words, I don't speak for anyone other than myself.  So, don't assume I am the official spokesperson for anyone.