Archive for January, 2010

DDD8

Today I went to the DeveloperDeveloperDeveloper day at the Microsoft campus in Thames Valley Park, Reading. It was a fantastic day with many great sessions covering a wide range of topics.

The first session I attended was “Mixing functional and object oriented approaches to programming in C#“ by Mark Needham from Thoughtworks. Mark discussed using functional programming techniques in C#. The talk focussed on using features of LINQ to replace imperative operations, such as for-each loops and if-else statements. Mark applied functional techniques at the operation-level and also at the structural-level, demonstrating how some common “Gang Of Four” patterns can implemented using a functional approach, by passing functions instead of interface implementations.

Mark recommended the book “Real-World Functional Programming” as a good resource on functional programming techniques.

The next session I attended was “Commercial Software Development – Writing Software Is Easy, Not Going Bust Is The Hard Bit” by Liam Westley. Liam gave an informative and entertaining talk on tactics he found useful when running a software development company. His tips included:

  • Offering customers an alternative to phone-based support to avoid interruptions.
  • Using automated unit tests and functional tests to prevent bugs from reaching production only to be discovered by your users. Liam said for him, automated testing didn’t immediately increase productivity, but over time has enabled him to develop high-quality software faster, resulting in satisfied customers.
  • Having good logging and error notifications. This enabled Liam to quickly identify and fix problems, sometimes before the customer had even raised the issue.
  • Get organised by tracking time, thoroughly reading and understanding contracts, always having an agenda for meetings and keeping a detailed history of support calls.
  • Improve your sales pitches by researching the business you are selling to and focusing on delivering value to the business, not just a set of features. He also recommends using light-weight specification documents that allow for change and spreading costs over time.

Liam suggested a good book on software product pricing called “Don’t Just Roll The Dice”.

The last session for the morning was “C# 4” by StackOverflow superstar, Jon Skeet. Jon discussed the new features of C#4, including named parameters, improved COM-interop, generic variance (covariants, contravariants and invariants, oh my!) and dynamic typing.

During the lunch break there was a series of Grok talks. Several presenters gave short talks on using T4 templates, the features of CodeRush Xpress, tracking tasks using a personal Kanban board and an introduction to Albacore: a non-XML based build system.

The first session I attended after lunch was “C# on the iPhone with Monotouch” presented by Chris Hardy. MonoTouch allows you develop iPhone apps using C# on Mono, an open-source version of the .NET Framework. I was amazed at the tooling support and how well it integrated with the iPhone development tools. Chris said the MonoTouch team released support for the iPad within 24 hours of the SDK being released by Apple. You still need a Mac to develop, but the fact you can use C# and standard .NET libraries makes it easy for .NET developers to reuse their existing skills. Chris stressed that it’s still important to learn how to read Objective-C to follow the Apple documentation. The talk was very inspirational and I now might have to invest in a MacBook Pro 🙂

The last talk I went to was “Testing C# and ASP.Net applications using Ruby” presented by Ben Hall (who also happed to be celebrating his birthday, resulting in birthday cake and a chorus of Happy Birthday To You). Ben showed that Ruby can be used to create more readable tests than C#. He gave an example of testing a .NET web application using Cucumber, a Ruby-based Behaviour-Driven Development (BDD) framework. He used IronRuby for calling standard .NET libraries and demonstrated using WebRat for running the tests through a browser. Ben explained the tests can be run in the background by using a “headless“ browser. The RubyMine IDE includes extensive refactoring support and a Visual Studio-like experience. The browser-based tests ran much slower than standard unit tests and Ben suggests only automating high-value, happy-path scenarios.

Further information can be found in the book, Testing ASP.NET Web Applications, which Ben co-authored.

Thanks to the organisers, Microsoft and other sponsors for putting on a fantastic day.

Creating a Simple IoC Container

Inversion of Control (IoC) is a software design principle that describes inverting the flow of control in a system, so execution flow is not controlled by a central piece of code. This means that components should only depend on abstractions of other components and are not be responsible for handling the creation of dependent objects. Instead, object instances are supplied at runtime by an IoC container through Dependency Injection (DI).

IoC enables better software design that facilitates reuse, loose coupling, and easy testing of software components.

At first IoC might seem complicated, but it’s actually a very simple concept. An IoC container is essentially a registry of abstract types and their concrete implementations. You request an abstract type from the container and it gives you back an instance of the concrete type. It’s a bit like an object factory, but the real benefits come when you use an IoC container in conjunction with dependency injection.

An IoC container is useful on all types of projects, both large and small. It’s true that large, complex applications benefit most from reduced coupling, but I think it’s still a good practice to adopt, even on a small project. Most small applications don’t stay small for long. As Jimmy Bogard recently stated on Twitter: “the threshold to where an IoC tool starts to show its value is usually around the 2nd hour in the life of a project”.

There are many existing containers to choose from. These have subtle differences, but all aim to achieve the same goal, so it’s really a matter of personal taste which one you choose. Some common containers in .NET are:

While I recommended using one of the containers already available, I am going to demonstrate how easy it is to implement your own basic container. This is primarily to show how simple the IoC container concept is. However, there might be times when you can’t use one of the existing containers, or don’t want all the features of a fully-fledged container. You can then create your own fit-for-purpose container.

Using Dependency Injection with IoC

Dependency Injection is a technique for passing dependencies into an object’s constructor. If the object has been loaded from the container, then its dependencies will be automatically supplied by the container. This allows you to consume a dependency without having to manually create an instance. This reduces coupling and gives you greater control over the lifetime of object instances.

Dependency injection makes it easy to test your objects by allowing you to pass in mocked instances of dependencies. This allows you to focus on testing the behaviour of the object itself, without depending on the implementation of external components or services.

It is good practice to reduce the number of direct calls to the container by only resolving top-level objects. The rest of object-graph will be resolved through dependency injection. This also prevents IoC-specific code from becoming scattered throughout the code base, making it easy switch to a different container if required.

Implementing a Simple IoC Container

To demonstrate the basic concepts behind IoC containers, I have created a simple implementation of an IoC container.

Download the source and sample code here

This implementation is loosely based on RapidIoc, created by Sean McAlindin. It does not have all the features of a full IoC container, however, it should be enough to demonstrate the main benefits of using a container.

public class SimpleIocContainer : IContainer
{
    private readonly IList registeredObjects = new List();

    public void Register<TTypeToResolve, TConcrete>()
    {
        Register<TTypeToResolve, TConcrete>(LifeCycle.Singleton);
    }

    public void Register<TTypeToResolve, TConcrete>(LifeCycle lifeCycle)
    {
        registeredObjects.Add(new RegisteredObject(typeof (TTypeToResolve), typeof (TConcrete), lifeCycle));
    }

    public TTypeToResolve Resolve()
    {
        return (TTypeToResolve) ResolveObject(typeof (TTypeToResolve));
    }

    public object Resolve(Type typeToResolve)
    {
        return ResolveObject(typeToResolve);
    }

    private object ResolveObject(Type typeToResolve)
    {
        var registeredObject = registeredObjects.FirstOrDefault(o => o.TypeToResolve == typeToResolve);
        if (registeredObject == null)
        {
            throw new TypeNotRegisteredException(string.Format(
                "The type {0} has not been registered", typeToResolve.Name));
        }
        return GetInstance(registeredObject);
    }

    private object GetInstance(RegisteredObject registeredObject)
    {
        if (registeredObject.Instance == null ||
            registeredObject.LifeCycle == LifeCycle.Transient)
        {
            var parameters = ResolveConstructorParameters(registeredObject);
            registeredObject.CreateInstance(parameters.ToArray());
        }
        return registeredObject.Instance;
    }

    private IEnumerable<object> ResolveConstructorParameters(RegisteredObject registeredObject)
    {
        var constructorInfo = registeredObject.ConcreteType.GetConstructors().First();
        foreach (var parameter in constructorInfo.GetParameters())
        {
            yield return ResolveObject(parameter.ParameterType);
        }
    }
}

The SimpleIocContainer class has two public operations: Register and Resolve.

Register is used to register a type with a corresponding concrete implementation. When type is registered, it is added to a list of registered objects.

Resolve is used to get an instance of a type from the container. Depending on the Lifecycle mode, a new instance is created each time the type is resolved (Transient), or only on the first request with the same instance passed back on subsequent requests (Singleton).

Before a type is instantiated, the container resolves the constructor parameters to ensure the object receives its dependencies. This is a recursive operation that ensures the entire object graph is instantiated.

If a type being resolved has not been registered, the container will throw a TypeNotRegisteredException.

Using the Simple IoC Container with ASP.NET MVC

Now I am going to demonstrate using the container by creating a basic order processing application using ASP.NET MVC.

First we create a custom controller factory called SimpleIocControllerFactory that derives from DefaultControllerFactory. Whenever a page is requested, ASP.NET calls GetControllerInstance to get an instance of the page controller. We can then pass back an instance of the controller resolved from our container.

public class SimpleIocControllerFactory : DefaultControllerFactory
{
    private readonly IContainer container;

    public SimpleIocControllerFactory(IContainer container)
    {
        this.container = container;
    }

    protected override IController GetControllerInstance(Type controllerType)
    {
        return container.Resolve(controllerType) as Controller;
    }
}

We now need to set SimpleIocControllerFactory as the current controller factory in the global Application_Start handler.

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        var container = new SimpleIocContainer();

        BootStrapper.Configure(container);

        ControllerBuilder.Current.SetControllerFactory(new SimpleIocControllerFactory(container));
    }
}

In order for the SimpleIocControllerFactory to resolve an instance of the OrderController, we need to register the OrderController with the container.

Here I have created a static Bootstrapper class for registering types with the container.

public static class BootStrapper
{
    public static void Configure(IContainer container)
    {
        container.Register<OrderController, OrderController>();
    }
}

The controllers do not contain state, therefore we can use the default singleton lifecycle to create an instance of the controller only once per request.

When we run the application, the OrderController should be resolved and the page will load.

It is worth noting that the controller factory should be the only place we need to explicitly resolve a type from the container. The controllers are top-level objects and all our other objects stem from these. Dependency Injection is used to resolve dependencies down the chain.

To place an order we need to make a call to OrderService from the controller. We inject a dependency to the order service by passing the IOrderService interface into the OrderController constructor.

public class OrderController : Controller
{
    private readonly IOrderService orderService;

    public OrderController(IOrderService orderService)
    {
        this.orderService = orderService;
    }

    public ActionResult Create(int productId)
    {
        int orderId = orderService.Create(new Order(productId));

        ViewData["OrderId"] = orderId;

        return View();
    }
}

When we build and run the application we should get an error: “The type IOrderService has not been registered”. This means the container has tried to resolve the dependency, but the type has not been registered with the container. So we need to register IOrderService and its concrete implementation, OrderService, with the container.

public static class BootStrapper
{
    public static void Configure(IContainer container)
    {
        container.Register<OrderController, OrderController>();
        container.Register<IOrderService, OrderService>();
    }
}

The OrderService in turn has a dependency on IOrderRepository which is responsible for inserting the order into a database.

public class OrderService : IOrderService
{
    private readonly IOrderRepository orderRepository;

    public OrderService(IOrderRepository orderRepository)
    {
        this.orderRepository = orderRepository;
    }

    public int Create(Order order)
    {
        int orderId = orderRepository.Insert(order);
        return orderId;
    }
}

As the OrderService was resolved from the container, we simply need to register an implementation for IOrderRepository for OrderService to receive its dependency.

public static class BootStrapper
{
    public static void Configure(IContainer container)
    {
        container.Register<OrderController, OrderController>();
        container.Register<IOrderService, OrderService>();
        container.Register<IOrderRepository, OrderRepository>();
    }
}

Any further types are that required simply need to be registered with the container then passed as an argument on the constructor.

Most full-featured IoC containers support some form of auto-registration. This saves you from having do to a lot of one-to-one manual component mappings.

I hope I have demonstrated that IoC containers are not magic. They are in fact a simple concept that, when used correctly, can help to create flexible, loosely-coupled applications.

Software Development and Chaos Theory

After watching an excellent BBC documentary called The Secret Life of Chaos, I was interested to see if anyone had written about the association between chaos theory and the unpredictable nature of software development.

I came across these papers written in 1995 by L.B.S. Raccoon:

The Chaos Model and the Chaos Life Cycle

Raccoon (1995) The Chaos Model and the Chaos Life Cycle, in ACM Software Engineering Notes, Volume 20, Number 1, Pages 55 to 66, January 1995, ACM Press. (PDF available here).

The chaos model combines a linear problem-solving loop with fractals to suggest that a project consists of many interrelated levels of problem solving. The behaviour of a complex system emerges from the combined behaviour of the smaller building blocks.

The chaos life cycle defines the phrases of the software development life cycle in terms of fractals that show that all phrases of the life cycle occur within other phrases.

This suggests an iterative, outside-in development process, which is one of the fundamental principles of Behaviour-Driven Development (BDD).

The Chaos Strategy

Raccoon (1995) The Chaos Strategy, in ACM Software Engineering Notes, Volume 20, Issue 5, Pages 40 to 47, December 1995, ACM Press. (PDF available here).

The main rule in chaos strategy is always resolve the most important issue first. This reflects the Just-in-Time production ideology as promoted by Lean Software Development.

It’s interesting to note that today’s popular agile software methodologies use some of the principles of chaos theory as presented in these papers. It seems that software development is recognised as an example of complexity at work.

Agile software development follows a natural, evolving, chaotic cycle. The smallest variation in conditions can result in a massive difference in outcome. There will never be a way of accurately predicting the outcome of a complex software project. We simply have to accept chaos as a fact of life and embrace an evolutionary development process.