Tuesday, October 25, 2011

I need closure in life....

One of my favorite techiques is using functional programming (in both C# and ruby) to "template out" code with anonymous delegation. It's perfect for those situations where you don't want to create an interface (in C#) for the sole purpose of reusing code inside of classes. There are many other situations where the technique provides some elegance to reuse, but reusing it within classes makse it a very approachable technique.

A very simple example would be as follows :

[TestMethod]
public void ExecuteFunctionalTechnique()
{
    TryCatchTemplate(() => { new Babolat().StringRacquet(); });
}

private void TryCatchTemplate(Action body){
    try
    {
        body();
    }
    catch (Exception)
    {
        throw;
    }
  
}

It gets more fun when you have to return a value from the anonymous delegate and you don't want to commit  to a type (yay, generics). A simple example is as follows:

 BindSelect<IList<Role>>( selRoles, "ID""Name"Role.GetAllRoles );

private void BindSelect<T>(HtmlSelect securityDropDown, 
    string dataMemberName, 
    string dataText, 
    Func<T> collectionToBind)
{
    securityDropDown.DataSource = collectionToBind();
    securityDropDown.DataValueField = dataMemberName;
    securityDropDown.DataTextField = dataText;
    securityDropDown.DataBind();
}

Have fun!

No comments:

Post a Comment