Wednesday, December 22, 2010

C# Closure Constructors

I’ve been doing quite a lot of Javascript recently, one of the Javascript patterns I’ve been using extensively is Douglas Crockford’s closure based class construction. It just struck me today that you could do something similar in C#.

Here’s a cool cat:

public class Cat
{
protected Cat(){}

public static Cat New(string name)
{
return New(name, null);
}

public static Cat New(string name, Cat parent)
{
var self = new Cat();

self.GetParent = () => parent;
self.SayHello = () => "Hello, my name is " + name;
self.MakeKitten = kittenName => New(kittenName, self);

return self;
}

public Func<string> SayHello { get; protected set; }
public Func<Cat> GetParent { get; protected set; }
public Func<string, Cat> MakeKitten { get; protected set; }
}

Which you can use like this:
 
var cat = Cat.New("Timmy");
var kitten = cat.MakeKitten("Jenny");

Console.WriteLine(kitten.SayHello());
Console.WriteLine(kitten.GetParent().SayHello());

Which outputs:

Hello, my name is Jenny
Hello, my name is Timmy

The interesting thing is that you don’t have to declare any private class fields, all the state is encapsulated by the closures created in the constructor. It would be easy to define different Cat behaviours just by providing different implementations of SayHello, GetParent and MakeKitten at runtime.

What do you think? Could there be any benefits to creating classes like this? Obvious drawbacks?

Don’t take this too seriously, I’m not for a moment suggesting that you refactor your code.. just playing :)

Tuesday, December 21, 2010

The Second Commandment: Thy entity shalt not participate in dependency resolution

Following on from my First Commandment a while back, I’d like to talk about a second mistake that a lot of people make when getting started with IoC containers. They worry about getting their domain entities sourced from the container, or participating in dependency resolution in some way. Domain entities should be POCO classes, they shouldn’t participate in dependency resolution.

Most business applications have ‘domain entities’ AKA ‘business objects’ usually something like this:

public class Car
{
public void Start()
{ ... }

public IEnumerable<Wheel> Wheels
{
get { return ...; }
}
}

When you start using an IoC container it’s a natural reaction to think, ‘how do I get my Car from the container’ or ‘how can my Car’s dependencies be resolved from the container’. You might see code like this for example:

public class Car
{
public IWheelRepository WheelRepository { get; set; }

public IEnumerable<Wheel> Wheels
{
get { return WheelRepository.GetWheelsFor(this); }
}
}

Along with code like this:

var car = container.Resolve<Car>();

This is wrong.

The general rule is that the domain model shouldn't have any outward facing dependencies, so you shouldn't be asking them to reference components from the container. The worst example of this is the Active Record pattern where domain entities are also responsible for their persistence. If you have a Customer object with methods like 'Save' and 'Update' you are breaking this rule.

The persistence problem is easy to solve, simply de-couple your domain class from its persistence. You now have a Customer and a CustomerRepository or maybe an IRepository<Customer>, I like the last one. Modern ORMs like NHibernate make this easy to do.

But what if your business logic requires you to do something with the 'outside world', like send  an email?

Say I have an Order domain entity that has a rule: when the order is confirmed, send the customer a confirmation email. I probably feel like I want to do something like this:

public class Order
{
private readonly IEmailSender emailSender;

public Order(IEmailSender emailSender)
{
this.emailSender = emailSender;
}

public void Confirm()
{
// ...
var confirmationEmail = CreateConfirmationEmail();
emailSender.Send(confirmationEmail);
}
}

But if my Order is not resolved from the container, how can I inject the IEmailSender?

There seem to be 3 main ways people solve this problem, each with its pros-and-cons...

1. Factor your business logic into a domain service, so I now have an Order class and an OrderService with a Confirm(Order order) method, the OrderService can be resolved from the container and have a dependency on the IEmailSender.

public class OrderService
{
private readonly IEmailSender emailSender;

public OrderService(IEmailSender emailSender)
{
this.emailSender = emailSender;
}

public void Confirm(Order order)
{
// ...
var confirmationEmail = CreateConfirmationEmail();
emailSender.Send(confirmationEmail);
}
}

The problem with this, is that we're now loosing encapsulation, our Order class' functionality is leaking out into domain services and it's ending up being just a property bag; the anaemic entity anti-pattern. We're not doing object oriented programming any more.

2. Inject the IEmailSender into the Order's confirm method: Order.Confirm(IEmailSender emailSender). Now we can get the IEmailSender from the container by doing constructor injection on the orchestrating class and simply pass it in when we call Confirm.

public class Order
{
public void Confirm(IEmailSender emailSender)
{
// ...
var confirmationEmail = CreateConfirmationEmail();
emailSender.Send(confirmationEmail);
}
}

The problem now is that the dependencies of the Confirm operation have become the responsibility of the orchestrating class and it has to worry about getting an instance of IEmailSender from somewhere. This violates Separation of Concerns. It makes your Confirm method brittle as well, what happens if you decide you don't need to send an email at a later date? Do you then go and rewrite every consumer of Order?

3. Udi Dahan's domain events pattern or something like it. Here we raise an event from our Order class' Confirm method and then have a handler that sends the email. Because the handler is resolved from the container, it can have the IEmailSender passed in via constructor injection. The caller is unaffected, it just calls Order.Confirm() and we don't have domain logic leaking out of the Order entity.

public class Order
{
public void Confirm()
{
// ...
DomainEvent.Raise(new OrderConfirmedEvent(this));
}
}

public class SendEmailOnOrderConfirmHandler : IHandle<OrderConfirmedEvent>
{
public void Handle(OrderConfirmedEvent orderConfirmedEvent)
{
var confirmationEmail = CreateConfirmationEmail();
emailSender.Send(confirmationEmail);
}
}

The downside is that we now have a nasty static dependency on the DomainEvent.Raise call scattered throughout our domain model.

I've used all three of these techniques at different times. I tend to avoid 2, it's got the nastiest code smell, and I'd probably favour 3 these days, simply because I always tend to have an Entity super class that can wrap the DomainEvent.Raise call and I really like the emerging CQRS patterns that are closely related.

But whatever you decide to do, avoid getting into the trap where you try and resolve your domain entities from the container.

Sunday, December 12, 2010

An Explosion of Alternative Web Frameworks

I’ve had a very enlightening last few weeks. I’m talking about the explosion in the number of alternative web frameworks for .NET and especially the emergence of alternatives to our old friend, the core ASP.NET infrastructure. Although a lot of this work has been around for a while, I’ve only just become aware of it.

The world of open source .NET frameworks has been vibrant for some time now. We’ve had Monorail for years and more recently FubuMvc and OpenRasta. So far OpenRasta is the only one which has attempted to break away from the stranglehold of ASP.NET and build it’s own HTTP abstraction.

With OpenRasta as the exception, all the existing frameworks (including ASP.NET MVC) have been targeted at ‘traditional’ web applications. By that, I mean applications where the majority of formatting and execution occurs on the server and to the browser the application appears as little more than static HTTP. But all this is changing. Two things are radically altering the development landscape; HTML5 and Mobile apps. both of these require infrastructure optimised to build scalable RESTful JSON APIs. We also need frameworks that will deploy without requiring an IIS instance and that preferably work on Linux with Mono.

Elsewhere, in the world of open source dynamic languages, things have been moving very fast. Node.js and Sinatra have generated enormous interest, as have the flexibility of web middleware abstractions like Rack and WSGI.

With these as inspiration, new .NET web frameworks have been popping up all over the place. Even more exciting is the emergence of common abstractions, so that we may be able to assemble web application stacks like Lego. Read on…

Manos

The first new framework that came to my attention a few weeks back was Manos by Jackson Harper. This is a lightweight web framework for Mono inspired by node.js and Sinatra. It uses the same IO library, libev, as node.js. The Herding Code podcast interviewed Jackson recently. It’s well worth a listen.

Here’s a snippet of a simple Manos application:

public class HelloWorld : ManosApp {

    public HelloWorld ()
    {
        Get ("/", ctx => ctx.Response.End ("Hello, World"));
    }
}

As you can see there’s a very simple mapping of a route to a delegate. In this case the path ‘/’ maps to a delegate that returns “Hello World” and then completes. Because the context is passed as a an argument to the delegate that handles the request, it’s trivial write asynchronous applications. In the podcast Jackson claimed that he can handle 10,000 open connections in his tests, that’s impressive.

Nancy

The next  framework to come to my notice was Nancy by Andreas HÃ¥kansson. This framework is heavily influenced by Sinatra. Currently it only works with ASP.NET, but the intention is to make it server agnostic. Here’s a snippet:

public class Module : NancyModule
{
    public Module()
    {
        Get["/"] = parameters => {
            return "Hello World";
        };
    }
}

Nancy has a dictionary that maps routes to delegates and the return value of the delegate dictates the response.

Nina

Around about the same time I also became aware of Nina by Dotan Nahum. Nina is also inspired by Sinatra (do you get the name references?).  Nina is based on ASP.NET, I couldn’t see if there was any intention of making it work on other platforms. Here’s Nina’s hello world:

public class HelloWorld : Nina.Application
{
    public HelloWorld()
    {
        Get("/", (m,c) => Text("Hello World"));
    }
}

Again we see the same pattern, mapping a route to a delegate. This time the delegate takes NameValueCollection of parameters and the HttpContext as its arguments and returns the response. Nina seems a little more developed than Nancy. It’s got full integration for most of the existing .NET view engines for example.

Kayak

Just yesterday I listened to Benjamin van der Veen talking to Scott Hanselman on Hanselminutes about Kayak. Kayak, like Manos is a full web stack and I understood from the interview that it also uses, or will use, libev. Kayak, like the other frameworks here has a direct route to method mapping:

public class MyService : KayakService 
{
    [Path("/")]
    public void Root() 
    {
        Response.Write("Hello, world.");
    }
}

OWIN

OWIN stands for Open Web Interface for .NET. This is even more exciting than the explosion in innovation around web frameworks itself. It’s a standard interface between servers and frameworks, currently under intense discussion at the .NET HTTP Abstractions group. This is important, because once it becomes an adopted standard it will mean that any server should work with any framework. So for example, I will be able to run OpenRasta on libev, or maybe Manos on IIS.

It will enable separate innovation in severs and frameworks, so you’ll be able to take a high performance scalable sever and marry it with your framework of choice. More than that, it’ll enable independent development of web middleware. Say I want to write a compression library, I won’t have to choose a particular framework to host it in, I simply make it talk OWIN at both ends and it will plug into any combination of framework and sever.

Here is the interface as it currently stands, but remember it’s under intense development at the moment and is likely to change:

namespace Owin
{
    /// <summary>
    /// An HTTP application.
    /// </summary>
    public interface IApplication
    {
        /// <summary>
        /// Begins the asynchronous process to get the <see cref="IResponse"/>.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="callback">The callback.</param>
        /// <param name="state">The state.</param>
        /// <returns>The <see cref="IAsyncResult"/> that represents the asynchronous invocation.</returns>
        IAsyncResult BeginInvoke(IRequest request, AsyncCallback callback, object state);

        /// <summary>
        /// Ends the asynchronous process to get the <see cref="IResponse"/>.
        /// </summary>
        /// <param name="result">The result.</param>
        /// <returns>The <see cref="IResponse"/>.</returns>
        IResponse EndInvoke(IAsyncResult result);
    }
    
    /// <summary>
    /// The HTTP request provides the requested method, uri, headers, application items, and input body.
    /// </summary>
    public interface IRequest
    {
        /// <summary>
        /// Gets the request method.
        /// </summary>
        string Method { get; }

        /// <summary>
        /// Gets the requested uri.
        /// </summary>
        string Uri { get; }

        /// <summary>
        /// Gets the headers.
        /// </summary>
        /// <remarks>
        /// Each header key may have one or more values matching the HTTP spec.
        /// Example:
        ///   GET / HTTP/1.0
        ///   Accept: text/html;application/xml
        ///
        ///   Generates a headers dictionary with key "Accept" containing string "text/html;application/xml"
        /// </remarks>
        IDictionary<string, IEnumerable<string>> Headers { get; }
        
        /// <summary>Gets the application-specific items or settings.</summary>
        IDictionary<string, object> Items { get; }

        /// <summary>
        /// Begins the asynchronous read from the request body.
        /// </summary>
        /// <param name="buffer">The buffer.</param>
        /// <param name="offset">The offset.</param>
        /// <param name="count">The count.</param>
        /// <param name="callback">The callback.</param>
        /// <param name="state">The state.</param>
        /// <returns>An IAsyncResult that represents the asynchronous read, which could still be pending.</returns>
        /// <see href="http://msdn.microsoft.com/en-us/library/system.io.stream.beginread.aspx"/>
        IAsyncResult BeginReadBody(byte[] buffer, int offset, int count, AsyncCallback callback, object state);
        
        /// <summary>
        /// Ends the asynchronous read from the request body.
        /// </summary>
        /// <param name="result">The result.</param>
        /// <returns>The number of bytes returned from the stream.</returns>
        /// <see href="http://msdn.microsoft.com/en-us/library/system.io.stream.endread.aspx"/>
        int EndReadBody(IAsyncResult result);
    }
    
    /// <summary>
    /// The HTTP response provides the status, headers, and body from an <see cref="IApplication"/>.
    /// </summary>
    public interface IResponse
    {
        /// <summary>
        /// Gets the status code and description.
        /// </summary>
        /// <remarks>The string should follow the format of "200 OK".</remarks>
        string Status { get; }

        /// <summary>
        /// Gets the headers.
        /// </summary>
        /// <remarks>
        /// Each header key may have one or more values matching the HTTP spec.
        /// Example:
        ///   HTTP/1.1 200 OK
        ///   Set-Cookie: foo=bar
        ///   Set-Cookie: baz=quux
        /// 
        ///   Generates a headers dictionary with key "Set-Cookie" containing string ["foo=bar";"baz=quux"]
        /// </remarks>
        IDictionary<string, IEnumerable<string>> Headers { get; }

        /// <summary>
        /// Gets the body <see cref="IEnumerable&lt;object&gt;"/>.
        /// </summary>
        /// <returns>The response as an <see cref="IEnumerable&lt;object&gt;"/>.</returns>
        /// <remarks>
        /// The <see cref="IEnumerable&lt;object&gt;"/> is not guaranteed to be hot.
        /// This method should be considered safe to generate either a cold or hot enumerable
        /// so that it _could_ be called more than once, though the expectation is only one call.
        /// </remarks>
        IEnumerable<object> GetBody();
    }
}    

Read the spec for the interface here: http://owin.github.com/owin/

Like I said, these are very interesting times. Keep an eye on these projects, I expect we’ll all be building web applications very differently in a few years time.

Monday, December 06, 2010

Javascript: Defining Classes with Closures

Over the weekend I watched Douglas Crockford’s five part series on Javascript, Crockford on Javascript. Probably one of the best video introductions to a programming language I have ever seen.

The section I enjoyed the most was part 3, Function the Ultimate, especially the section where he discusses object creation. I’ve always disliked prototype based inheritance. It’s clumsy, awkward and lacks encapsulation. Crockford shows a much nicer object creation strategy based on closures, which looks something like this:

var animalsApp = (function(){

var new_animal = function(name) {
var animal = {};

animal.sayHello = function() {
return "Hello, my name is " + name;
}
return animal;
}

var new_dog = function(name) {
var dog = new_animal(name);

dog.bark = function() {
return "woof";
}
return dog;
}

var new_cat = function(name) {
var cat = new_animal(name);

cat.meow = function() {
return "eeooowww";
}
return cat;
}

return {
main: function(){
var dog = new_dog("rover");

console.log(dog.sayHello());
console.log(dog.bark());

var cat = new_cat("tom");

console.log(cat.sayHello());
console.log(cat.meow());
}
};
}());

animalsApp.main();

Using this technique we can create properly encapsulated objects. In the example above, our animalsApp only exposes a single function, main, new_animal, new_dog and new_cat are all private. The class definitions are very clear, any variables or functions defined in the constructor body are private and we only expose members that we explicitly attach to the object (dog.bark = function(){}).

You can run this example using node:

$ node closureclass.js
Hello, my name is rover
woof
Hello, my name is tom
eeooowww