time to read 2 min | 255 words

A while ago I added query batching support to NHibernate, so you can execute multiply queries to the database in a single roundtrip. That was well and good, except that you need to know, in advance, what you want to batch. This is often the case, but not nearly enough. Fairly often, I want disparate actions that would be batched together. It just occurred to me that this is entirely possible to do.

In my Rhino Igloo project, I have a lot of places where I have code very similar to this (except it can go for quite a while):

Users.DataSource = Controller.GetUsers();
Issues.DataSource = Controller.GetIssues();
Products.DataSource = Controller.GetProducts();

I solved the problem of batching those by figuring out in advance what I need and then doing a single batch query for all of them, then handing out the result through each of those methods.

This is complicated and sometimes fragile.

What would happen if I could ignore that and instead built API that looked like this?

public FutureOf<User> GetUsers();
public FutureOf<Issue> GetIssues();
public FutureOf<Product> GetProducts();

Where FutureOf<T> would be defined as:

public class FutureOf<T> : IEnumerable<T>

Now, what is special here, I hear you way. Well, when you start enumerating over a future, it gather all the future queries that has been created so far, executing them in a single batch against the database, and return the results.

Where before I needed to take special care to get this result, now it is just a naturally occurring phenomenon :-)

Neat, if I say so myself.