Sunday, March 28, 2010

Functional Dependency Injection == Currying

If, like me, you’ve been doing object oriented programming for a while, you’ll be familiar with Dependency Injection. Dependency Injection is a form of Inversion of Control where a class’s dependencies are provided as constructor arguments. Here’s an example:

class Reporter
{
    private readonly IReportRepository reportRepository;
    private readonly IReportSender reportSender;

    public Reporter(IReportRepository reportRepository, IReportSender reportSender)
    {
        this.reportRepository = reportRepository;
        this.reportSender = reportSender;
    }

    public void SendReportById(int id)
    {
        var report = reportRepository.GetReportById(id);
        reportSender.SendReport(report);
    }
}

When we instantiate an instance of Reporter, we provide implementations of both IReportRepository and IReportSender. We then call SendReportById which executes methods on both of these dependencies. It’s a two stage process:

1. Create a Reporter with the dependencies it needs to do its job.
2. Execute the Reporter.

In a functional language like F# we can do the same thing without the overhead of having to declare classes and interfaces. We can also do the same thing in C#, but it requires some jiggery-pokery, so I’m going to show you it in F#.

let reporter reportRepository reportSender id =
    let report = reportRepository id
    reportSender report

Note: three lines of code verses nine for the C# version.

Here we’re defining a reporter function that takes three arguments, a reportRepository, a reportSender and an id. Internally it does exactly the same as our Reporter class above. In our object oriented version, we explicitly defined the dependencies as constructor arguments so that we can supply dependencies independently of executing the SendReportById method. But because functional languages support currying, we don’t need those constructor arguments, we can partially apply the function instead. We can call reporter with just the first two arguments to create a curried version of reporter that already has the reportRepository and reportSender dependencies satisfied. It’s then just waits for the last argument, the ‘id’ value, in order to execute.

If we execute this definition in F# interactive we see that it has this type:

val reporter : ('a -> 'b) -> ('b -> 'c) -> 'a -> 'c

We can see that it takes two functions and a value and returns a value. We can also see that F# functions are curried by default. We can pass just the first two arguments (‘a –> b’) –> (‘b –> ‘c) and the return value will be ‘a –> ‘c.

Let’s define two simple implementations of reportRepository and reportSender:

type report = { id:int; title:string; body:string }

let myReportRepository id =
    { id = id; title = "Great Report"; body = "The report body" }

let myReportSender report =
    printfn "report = %A" report

New we can build a report sender that uses these two functions as dependencies:

let myReporter = reporter myReportRepository myReportSender

Now myReporter is equivalent to an instance of our Reporter class above. When we execute it, it’s the same as calling myReporter.SendReportById(someId):

> myReporter 10;;

report = {id = 10;
 title = "Great Report";
 body = "The report body";}
val it : unit = ()

One could argue that the whole paraphernalia of object oriented programming is simply to make up for the lack of currying.

Wednesday, March 24, 2010

Selenium test suite for Suteki Shop

I have finally got around to checking out Selenium. Selenium, if you don’t know, is an open source browser automation package that you can use to create automated tests for your web application. It’s most basic form is a Firefox plug-in, Selenium IDE, that is incredibly easy to use. You simply click around your application and it records what you are doing. You can then play back those actions as test cases. I went from knowing nothing about Selenium to having a working set of test cases in a couple of hours, and most of that time was spent recording the tests. I only had to do a little googling to work out how to deal with the TinyMCE WYSIWYG editor we use for the product descriptions.

I’ve recorded some basic test cases for Suteki Shop (my little open source eCommerce application). To try them out, do the following:

1. Download and install Selenium IDE from here.

2. Get the latest Suteki Shop source code from the Google Code repository here.

3. Create the SutekiShop SQL Server database in localhost\SQLEXRESS by running in the numbered database creation scripts in <your source location>\sutekishop\Database

4. Open the SutekiShop solution in Visual Studio. Make sure that the Suteki.Shop project is set as the start-up project and hit ctrl-F5 to run it. You should see suteki shop in your browser. Make sure it’s the active window in Firefox (not IE!).

5. Open Selenium IDE by clicking on Tools –> Selenium IDE in Firefox.

6. In the Selenium IDE choose File –> Open Test Suite and select <your source location>\sutekishop\Selenium_test_scripts\SutekiShop_test_suite.html

Note: You will have to change the location of the image files in the Product_Edit_Surprise_Add_Images and the Product_Edit_Victory_Add_Images test cases. Change the images paths to start from your source location, so for example change:
E:\\Source\\sutekishop\\Selenium_test_scripts\\Images\\surprise1.jpg
to
<Your source location>\\sutekishop\\Selenium_test_scripts\\Images\\surprise1.jpg

If anyone can tell me how to use a relative path from the selenium test case here I would be much obliged.

7. Click the ‘Play Entire Test Suite’ icon in Selenium IDE. You’ll see Selenium automatically run the application through some basic tests.

SeleniumTests 
If you write web applications of any kind you should check out Selenium. I’ve still to explore the advanced features, but for quickly putting together simple regression tests it’s very nice.

Tuesday, March 23, 2010

Why I write this stuff

I just got a comment on my post Currying in C# with Oliver Sturm:

Re-implementing something that has been around for decades is hardly interesting. It's just syntactic sugar. I know that some people are eager to put this on their CV so they will probably re-write their entire codebase, using this and other such C# 3.0/4.0 constructs, which is sad really. Using currying for anything other than the simplest examples is wrong, as we have things called methods which are much cleaner, clearer and understandable:
int Add(int x, int y)
{
return x+y;
}

So I started to write a reply, but sometimes comments are too good an opportunity for making a point, so I’ve promoted the comment and my reply to a full post.

The original post was something I wrote after attending a talk by Oliver Sturm. It was one of those ‘light bulb’ moments for me and I’m still trying to work out the implications of Oliver’s talk two years later. Currying is a pretty easy concept to understand, the harder part is getting why it’s useful and how you can use it.

So why would we create a curried version of a function? The point is that you can partially apply curried functions. It's a very powerful technique somewhat like a functional version of dependency injection. I tried to explain my understanding of this in my post Thought Experiment: The Curry Facility.

So now for my rant.

This has nothing to do with CVs. It has nothing to do with showing off or trying to get a better paid job. Believe me, over ten years of working as a contractor and going to interviews several times a year has taught me that nobody cares about this stuff. Certainly no corporate project manager who’s looking for a C# developer. In fact it’s likely to scare people off. If you want an effective CV, just stuff it full of the latest drag-and-drop visual tools from Microsoft. If you simply care about squeezing the most cash from your clients, learn how to configure Sharepoint or Microsoft CRM. Wear a suit, learn how to make excuses, exaggerate and sell sell sell.

Nope, this is about the love of programming. I’m not a particularly good programmer, but I do get a huge amount of intellectual satisfaction from it. I started this blog because I wanted to share my enthusiasm and express the joy I get from playing with this stuff. I don’t really care if it’s useful (although I think most of it is) and I don’t really care whether people read it or like it (although it’s very satisfying when they do). Functional programming is awesome and if you don’t agree with me, you’ve come to wrong the place.

Upgrading Suteki Shop to ASP.NET MVC 2

I spent the last two mornings upgrading my little open source eCommerce application, Suteki Shop, to ASP.NET MVC 2. On the whole it was pretty straightforward with only a few code changes required, which I’ll talk about below. So how do you go about doing the upgrade? Here are the steps I took:

1. I downloaded and installed ASP.NET MVC 2, you can get the installer from here:
http://www.microsoft.com/downloads/details.aspx?FamilyID=c9ba1fe1-3ba8-439a-9e21-def90a8615a9&displaylang=en

2. I read the upgrade notes:
http://www.asp.net/learn/whitepapers/aspnet-mvc2-upgrade-notes/

3. …Which suggested I use Eilon Lipton’s upgrade wizard. Eilon is one of the core developers on the MVC team at Microsoft, so I guessed it would be easiest just to let him do it :) You get his wizard here:
http://weblogs.asp.net/leftslipper/archive/2010/03/10/migrating-asp-net-mvc-1-0-applications-to-asp-net-mvc-2-rtm.aspx

MVC2UpgradeWizard

The wizard ran without any errors. Checking the changes with tortoise svn looked like this:

MVC2UpgradeWizard_TortoiseView

The changes were:

- Suteki.Shop.csproj
      - Changed the project type guid
      - Changed the System.Web.Mvc version to 2.0.0.0 (I needed to copy the new Assembly to my dependencies folder and updated the reference path)
      - Added a reference to System.ComponentModel.DataAnnotations
- Every other csproj file
      - Changed the System.Web.Mvc version to 2.0.0.0 (I needed to copy the new Assembly to my dependencies folder and updated the reference path)
      - Added a reference to System.ComponentModel.DataAnnotations
- Added a load of new jQuery and MicrosoftAjax javascript files to ~/Content/Scripts
- Changed all the MVC references in my Web.config files to point to the new assembly, adds a bindingRedirect from v1 to v2

4. I built the solution and got 6 errors initially

MVC2Upgrade_Initial_build_errors

5. Starting to fix the compile errors, I had to do the following:

-  Had to change some of my HtmlHelper extension methods to use MvcHtmlString instead of string.
-  ModelBindingContext.ValueProvider doesn't have an indexer any more, had to change some code to use the GetValue method.
-  ModelBindingContext.ModelType is now provided by ModelMetadata, so unit tests for custom binders had to change from:

context = new ModelBindingContext()
{
  ModelName = "foo", 
  ModelType = typeof(TestEntity),
  ModelState = new ModelStateDictionary()
};

to

context = new ModelBindingContext()
{
    ModelName = "foo", 
    ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(TestEntity)),
    ModelState = new ModelStateDictionary()
};

- Mocking HtmlHelper: the ViewContext constructor now requires a TextWriter argument.

6. Added the new MVC Futures assembly from
http://aspnet.codeplex.com/releases/view/41742

7. Added the latest version of MvcContrib which I downloaded from
http://teamcity.codebetter.com/

I also upgraded all my Castle project references with the ones from MvcContrib.

This was the minimum possible upgrade effort. The next task will be to look at all the nice new features in both the core MVC Framework and the latest version of MvcContrib and see what bits I can use in Suteki Shop.

Monday, March 08, 2010

How to tell if a type is a delegate

If you are holding a reference to a type, how can you tell if it’s a delegate? I expected there to be an ‘IsDelegate’ property on Type, but it isn’t there. The way I’ve found to do it, is to test if the type’s BaseType property inherits from System.MulticastDelegate.

public bool IsDelegate(Type type)
{
    return typeof (MulticastDelegate).IsAssignableFrom(type.BaseType);
}

Now this code:

Console.WriteLine("string    {0}", IsDelegate(typeof(string)));
Console.WriteLine("int       {0}", IsDelegate(typeof(int)));
Console.WriteLine("Func<int> {0}", IsDelegate(typeof(Func<int>)));
Console.WriteLine("Test      {0}", IsDelegate(typeof(Test)));

Will output this:

string    False
int       False
Func<int> True
Test      True

Do you know a better way?

Update: ‘Test’ in the example is defined like this:

public delegate int Test(int a, int b);

Thanks @Daneel3001 :)

Thursday, March 04, 2010

Combining Higher Order Functions in C#

Say I have a higher-order-function, ‘applier’, that takes another function and some arguments, applies the function to the arguments and returns the results multiplied by two:

Func<Func<int, int, int>, int, int, int> applier = (f, x, y) => f(x, y) * 2;

Now let’s say we have a function, ‘multiplier’ that simply multiplies two numbers:

Func<int, int, int> multiplier = (a, b) => a*b;

How can we combine applier and multiplier so that we end up with a function that simply multiplies two numbers and doubles the result?

First we curry applier:

var curried = Functional.Curry(applier);
 
So now ‘curried’ looks something like this:
 
Func<Func<int, int, int>, Func<int, Func<int, int>>> curried = f => x => y => f(x, y)*2;

It’s a function that takes a function and returns a function. So if we call it passing in ‘multiplier’ we should get back a function that does what we want:

var curriedCombined = curried(multiplier);

The only problem with ‘curriedCombined’ is that it’s in this curried form:

Func<int, Func<int, int>> curriedCombined = x => y => (x*y)*2;

So let’s DeCurry it (is there a better term for this?):

var combined = Functional.DeCurry(curriedCombined);

Now we have our target function. We can call it just like a normal delegate with two arguments:

Console.WriteLine("combined(4) = {0}", combined(4, 4));

Which outputs 32 as expected.

So now we have a nice mechanical way of turning higher-order-functions into normal functions by doing the following:

  1. Curry the higher-order-function
  2. Pass the function(s) that supply the function argument(s) into the curried version.
  3. DeCurry

All I have to do now is some serious reflection and I’ll have a working CurryFacility.

Here is my Functional class (stolen from Oliver Sturm)

using System;

namespace Mike.AdvancedWindsorTricks.Model
{
    public class Functional
    {
        public static Func<T1, Func<T2, T3>> Curry<T1, T2, T3>(Func<T1, T2, T3> function)
        {
            return a => b => function(a, b);
        }

        public static Func<T1, Func<T2, Func<T3, T4>>> Curry<T1, T2, T3, T4>(Func<T1, T2, T3, T4> function)
        {
            return a => b => c => function(a, b, c);
        }

        public static Func<T1, Func<T2, Func<T3, Func<T4, T5>>>> Curry<T1, T2, T3, T4, T5>(Func<T1, T2, T3, T4, T5> function)
        {
            return a => b => c => d => function(a, b, c, d);
        }

        public static Func<T1, T2, T3> DeCurry<T1, T2, T3>(Func<T1, Func<T2, T3>> function)
        {
            return (a, b) => function(a)(b);
        }

        public static Func<T1, T2, T3, T4> DeCurry<T1, T2, T3, T4>(Func<T1, Func<T2, Func<T3, T4>>> function)
        {
            return (a, b, c) => function(a)(b)(c);
        }

        public static Func<T1, T2, T3, T4, T5> DeCurry<T1, T2, T3, T4, T5>(Func<T1, Func<T2, Func<T3, Func<T4, T5>>>> function)
        {
            return (a, b, c, d) => function(a)(b)(c)(d);
        }
    }
}

Monday, March 01, 2010

Thought experiment: The Curry Facility

Please indulge me for a while, I’ve been considering how to leverage the beauty of functional programming techniques and higher order functions but with the flexibility of an IoC container.

Imagine we have a couple of components that we want to register with our IoC container:

public class ComponentOne
{
    private readonly ComponentTwo componentTwo;

    public ComponentOne(ComponentTwo componentTwo)
    {
        this.componentTwo = componentTwo;
    }

    public SomeOutput SomeOperation(string someParameter)
    {
        var input = new SomeInput { SomeParameter = someParameter };
        return componentTwo.SomeOperation(input);
    }
}

public class ComponentTwo
{
    public SomeOutput SomeOperation(SomeInput input)
    {
        return new SomeOutput {SomeOtherParameter = input.SomeParameter};
    }
}

Nothing unusual here. Now, ComponentTwo is simply a place to put the function SomeOperation, there’s no other need for it to exist. We could just as well supply a delegate to ComponentOne:

public class ComponentOne
{
    private readonly Func<SomeInput, SomeOutput> getInput;

    public ComponentOne(Func<SomeInput, SomeOutput> getInput)
    {
        this.getInput = getInput;
    }

    public SomeOutput SomeOperation(string someParameter)
    {
        var input = new SomeInput { SomeParameter = someParameter };
        return getInput(input);
    }
}

public static class FunctionsTwo
{
    public static SomeOutput SomeOtherOperation(SomeInput input)
    {
        return new SomeOutput { SomeOtherParameter = input.SomeParameter };
    }
}

FunctionsTwo is just somewhere to put SomeOperation. Everything is static so we can consider it somewhat like a module or a namespace, it serves no other purpose.

We can already register this with Windsor like so:

var container = new WindsorContainer()
    .Register(
        Component.For<ComponentOne>(),
        Component.For<Func<SomeInput, SomeOutput>>().Instance(FunctionsTwo.SomeOtherOperation)
    );

var componentOne = container.Resolve<ComponentOne>();

var output = componentOne.SomeOperation("Hello World");

// writes "Hello World" to the console
Console.WriteLine(output.SomeOtherParameter);

But what about ComponentTwo, do we really need a class for our ‘SomeOperation’ method to live in? How about if we replace it with a higher order function:

public static class FunctionsOne
{
    public static SomeOutput SomeOperation(Func<SomeInput, SomeOutput> getInput, string someParameter)
    {
        var input = new SomeInput { SomeParameter = someParameter };
        return getInput(input);
    }
}

Rather than providing the delegate as a private field of our class, that we expect to be passed as a constructor parameter, we simply provide it as the first argument of our SomeOperation method. It’s a classic example of a higher order function.

I’ve covered currying before, go and read my post on the subject if you haven’t encountered it. Languages like F# provide currying out of the box - thus F# functions only ever have one argument. You have to work a lot harder to make it work with with C#, but what if your IoC container could do the currying for you?

Now imagine we had a ‘CurryFacility’ so that we could do something like this:

var container = new WindsorContainer()
    .AddFacility<CurryFacility>()
    .Register(
        Component.For<Func<string, SomeOutput>>().SuppliedBy(FunctionsOne.SomeOperation),
        Component.For<Func<SomeInput, SomeOutput>>().SuppliedBy(FunctionsTwo.SomeOtherOperation)
    );

var getOutput = container.Resolve<Func<string, SomeOutput>>();

// writes "Hello World" to the console
Console.WriteLine(getOutput("Hello World"));

We’ve registered a service ‘Func<string, SomeOutput>’ but supplied a ‘Func<Func<SomeInput, SomeOuput>, string, SomeOutput>’. My imaginary CurryFacility would notice that to match the requested signature it would have to supply a delegate ‘Func<SomeInput, SomeOutput>’, which it would simply resolve as normal, and then partially apply SomeOperation to satisfy the service. I didn’t have time tonight to make it work, I but can’t see it being particularly painful to implement.

I’m very excited about the possibilities of functional programming, it allows us concisely describe problems without all the noise an OO language traditionally requires. In many cases a higher order function is a far more concise way of expressing the same thing as a class with DI’ed dependencies and a single method.

The CurryFacility doesn’t exist yet, but I’m going to have a go at putting something together. I’m not aware of anything like this existing already, but then I don’t follow the other .NET IoC containers. Let me know if someone’s already got an implementation.