Showing posts with label design pattern. Show all posts
Showing posts with label design pattern. Show all posts

Tuesday, 25 August 2015

Conway's Game of Life: An Exercise in WPF, MVVM and C#

This blog post was written for the Lockheed Martin Insight blog, sharing here for the external audience.

Last month I started the Pluralsight summer camp by watching an interesting video in which the presenter implements Conway's Game of Life using HTML, CSS and JavaScript. The video inspired me to write an MVVM based implementation of the game using Windows Presentation Foundation (WPF) and C#. There were two aims to this exercise. The primary was for me to reacquaint myself with WPF, which is a framework I've been wanting to spend some time with for a while. And the secondary was to implement something fun.

The purpose of this blog post is to document the exercise. We'll cover what Conway's Game of Life is, a bit about the design and then see how some WPF and .NET framework features help in implementing an MVVM solution. The source code for the implementation is available on GitHub.

So, what is Conway’s Game of Life?

The Game of Life is a popular cell automaton algorithm that simulates the evolution of life. The algorithm was designed by British mathematician John Conway and has gained popularity for its simplicity. In its purest form, the universe for the Game of Life is represented by a grid which has an infinite number of cells. Each grid cell can contain a dead or living cell. The game starts with the user providing a seed generation of living cells. Based on the initial generation of cells, the universe evolves through generations to simulate evolution. For a generation to evolve, the following four rules are applied to the current generation:

  1. Any live cell with fewer than two live neighbours dies (due to under-population).
  2. Any live cell with two or three live neighbours lives on to the next generation.
  3. Any live cell with more than three live neighbours dies, (due to overcrowding).
  4. Any dead cell with exactly three live neighbours becomes a live cell (by reproduction).

And that's it. By applying these four rules, it is surprising to see how a universe can evolve to create complex symmetrical patterns, even when there is no symmetry or pattern in the seed generation.

Arriving at an Object-Oriented Design

The MVVM architectural design pattern was adopted to achieve a clear separation of concerns. I started by identifying the models:

  • Cell Model: Represents a single cell in the universe. Encapsulates data for the cell's position and whether it is dead or alive.
  • Generation Model: Represents a generation of life. Encapsulates data on the size of the universe, the cells within the universe and provides functionality to alter the living state of cells.

The EvolutionEngine class was identified to hold the current generation and take on the responsibilities of:

  • Evolving the current generation to the next generation, as per the rules of evolution.
  • Detecting if the current generation can no longer evolve.
  • Keeping track of the number of generations that the current generation has evolved through.
  • Resetting the generation back to an empty state.

A single view-model was identified, namely, GenerationViewModel. The view-model uses the EvolutionEngine class to:

  • React to actions that originate from the view.
  • Provide information for the view to display.
  • Provide notifications to the view if the observed information changes.

In summary, we have a couple of models, an engine class to work with the models and a view-model to keep the view in sync with the models.

Writing the MVVM WPF Implementation

The following diagram illustrates how the components of an MVVM solution are related in WPF (image source).

A view is built using the eXtensible Application Markup Language (XAML). The association between a view and its view-model is accomplished through the DataContext property of the view. Controls in a view are bound to properties in the view-model using the data binding features of WPF. In a scenario where the view-model is only serving as a proxy between the view and model, you may consider the use of a view-model superfluous and let the view-model expose the underlying model (see the "Why Use a ViewModel?" section in an MSDN article). Actions performed on the user interface are encapsulated in commands that are exposed by the view-model (using the Command design pattern). We will see how a view-model exposes its supported commands using the ICommand interface. Finally, notifications are raised as C# events from the view-model. The INotifyPropertyChanged interface is used primarily for this purpose.

As I’ve alluded to, there are a number of useful features in WPF and .NET that assist in the implementation of an MVVM solution. The particular features that I’m referring to are:

  • The FrameworkElement.DataContext property.
  • Using the Binding class to associate parts of the view to the view-model.
  • Raising notifications through the INotifyPropertyChanged interface.
  • Converting incompatible data between bound properties using the IValueConverter interface.
  • Encapsulating and executing actions using the ICommand interface.

Each of these features were used in the implementation for the game. In the sections below, we will discuss what each of these features are and see examples of how they were adopted in the solution.

Setting the Data Context and specifying a Binding

The Grid control was a natural choice to visually represent the universe. Each cell of life within the universe is represented by a TextBlock control. The code snippet below shows how the TextBlock is created:

In WPF, user interface controls derive from the FrameworkElement class which contains an important property named DataContext. The DataContext property of a control is set to an object that the control uses to pull its data from and/or push its data to. This object is typically a view-model or model instance. By setting the TextBlock.DataContext property to an instance of the Cell model we can bind properties of the TextBlock control to properties of the Cell model.

Aside: As a WPF view is hierarchical, a nice feature of using the DataContext property is that it can be inherited from a parent user interface control.

In our Game of Life implementation, we use the Background (colour) property of the TextBlock control to indicate whether the cell is dead or alive. On lines 7-10 of the CreateCellTextBlock method, you’ll see that we call the SetBinding method. The first parameter to this method specifies which property we want to set the binding for (made possible with Dependency Properties) and the second parameter accepts a Binding instance.

The Binding instance is created by the following method:

There are a few things to note here. Firstly, the Binding object supports a Source property which we do not explicitly set. The reason for this is that if no Source property is set on a binding, the binding defaults to using the DataContext property on the control that the binding is set on. In this case, the TextBlock control’s DataContext property is already set to a Cell model instance. We can therefore set the Path property to point to a particular property within the model, in this case the boolean Cell.Alive property.

The Mode property is set to the enumeration value of BindingMode.TwoWay, meaning that any change to the TextBlock control through the user interface updates the model and conversely any change to the model updates the user interface. To support two-way binding, the Cell model will need to implement the INotifyPropertyChanged interface so that any change to the Alive property is notified to the view.

Implementing Notifications with INotifyPropertyChanged

The INotifyPropertyChanged interface is implemented by classes that need to notify clients (in our case, the view) that an observed property value has changed. Typically, this interface is implemented by view-models or models that want to broadcast changes to certain property values.

INotifyPropertyChanged supports one member, the PropertyChanged event. If you have a two-way binding setup between a user interface control property and a view-model property, programmatic changes to the view-model property will not be reflected in the user interface unless the view-model implements INotifyPropertyChanged and the observed property’s setter raises the PropertyChanged event.

In our solution, we wrote a reusable ObservableBase class that implements INotifyPropertyChanged. The Cell and GenerationViewModel classes both inherit from ObservableBase.

The PropertyChanged event is raised from the OnPropertyChanged method which accepts a single parameter – the name of the property that has changed. The CallerMemberName attribute is used so that we can call this method without having to specify a hardcoded string with the property name. The code below shows the implementation for the Cell model, which inherits from ObservableBase.

Notice how the Alive property setter calls the OnPropertyChanged event. An unfortunate side effect of implementing INotifyPropertyChanged is that you’re unable to use automatic properties for the properties that need to raise the notification event.

Converting Between Bound Properties Using IValueConverter

In our earlier code snippet for the CreateCellAliveBinding method, you may have noticed that we also set the Binding.Converter property. The Converter property is used when we bind two properties that have a type mismatch or expect data in different formats. To recap, we are using the Background (colour) property of the TextBlock to indicate if the cell represented by the TextBlock is dead or alive. The Alive property on our Cell model is of boolean type, therefore, we need our binding to convert the boolean value to a colour. This is where the IValueConverter interface is used to take on the role of an adapter.

The implementation of the IValueConverter is in the class LifeToColourConverter, shown below:

The IValueConverter interface supports two methods, namely, Convert and ConvertBack. The Convert method is used when binding the value from the source property (Cell.Alive) to the target property (TextBlock.Background). Conversely, the ConvertBack method is used when updating the source from the target. If you are only using one-way binding, then you are only required to provide an implementation for the Convert method (the ConvertBack method can safely throw the NotImplementedException).

Handling User Interface Actions Using the Command Design Pattern

A view-model exposes a set of actions that are encapsulated within commands. Commands are exposed as properties on the view-model so that user interface controls can bind to them. The logic for a command is encapsulated within a class that implements ICommand. The ICommand interface supports two methods; CanExecute and Execute. The CanExecute method returns a boolean value which determines whether the command can execute. The Execute method contains the command logic to run.

In our solution, the view's DataContext is set to an instance of the GenerationViewModel class. In this view-model, we expose the following three commands:

RelayCommand is a popular implementation of the ICommand interface which has been available as open source for some while. We are using a particular variant of RelayCommand which enables a single parameter to be sent to the method that ultimately executes the command. You can view how the three command properties are initialised and the implementations for the CanExecute/Execute methods in the GenerationViewModel class.

An advantage of the RelayCommand implementation for ICommand is that it achieves reusability by using the Predicate and Action delegates to reference the CanExecute and Execute methods respectively. This avoids the need for writing a separate ICommand implementation for every command that the game supports.

In the user interface for the game, we have two buttons. One button binds to the view-model EvolveCommand property and the other binds to the ResetCommand property. The XAML snippet below shows how the command bindings are created:

If the ICommand.CanExecute method returns false for a command that is bound to a button, the button is automatically disabled.

The ToggleCellLifeCommand is executed when the user is setting up the initial generation of living cells, the binding for this command is setup programmatically by the following method (called by the CreateCellTextBlock method shown earlier):

We are using the InputBinding class to specify that a left mouse click on the TextBlock should execute the ToggleCellLifeCommand and pass it a formatted string that contains the cell position. The ToggleCellLifeCommand method implementation in the GenerationViewModel class looks up the cell and toggles the Alive property boolean value. As we have an active binding between each TextBlock and its Cell.Alive property, the TextBlock colour will automatically change to a colour that represents the current value for the Alive property.

Summary

In this post, we’ve introduced and described some of the main features that WPF and the .NET framework provide for implementing MVVM based solutions. Conway’s Game of Life served as a fun exercise to use these features with.

We saw how the FrameworkElement.DataContext property enables seamless binding between user interface controls and properties on view-models. Two-way binding was shown to be possible using the INotifyPropertyChanged interface as a mechanism to notify the view of changes in the view-model. We introduced a useful ObservableBase class which implements INotifyPropertyChanged and can be reused in future WPF projects that need to support two-way binding. To bind two properties that work with different data types, we saw how an implementation of the IValueConverter interface can be used as an adapter. Finally, we saw how the command pattern is used to encapsulate logic in an ICommand implementation and how commands are exposed as properties on a view-model that can be bound-to in the view.

The animated graphic below shows the finished game. In the animation, we see the evolution for a simple L-shaped seed pattern in a universe of 25x25 cells. Surprisingly, this basic seed pattern lives through eighteen generations of life with some fascinating symmetrical patterns before it stops evolving.

Full source code is available in a GitHub repository.

Saturday, 19 July 2014

Empty Collections

I was reading one of my favourite Java programming books this morning and came across a simple coding pattern that I've been practicing in C# since I first read this book. I feel it's a useful thing to share here. For those of you that are interested, the book is "Effective Java" by Joshua Bloch. It contains a series of bite sized chunks of tips/recommendations that Java developers can use. Although the book focuses on the Java programming language, I feel there are lots of things it discusses that are transferrable to any programming language. One of these tips is the topic of this post.

Joshua mentions that it's better to return empty collections rather than null when writing methods. The reason being that any code calling your method then doesn't need to explicitly handle a special null case. Returning an empty collection makes the null check redundant and results in much cleaner method calling code. In C#, the System.Linq.Enumerable class has a useful generic method called Empty. When called with a type parameter, this method returns an empty instance of IEnumerable<T> (where T is your type parameter).

An example use:
public class House
{
    public IEnumerable<Person> CurrentOccupants { get; set; }
        
    public House()
    {
        CurrentOccupants = Enumerable.Empty<Person>();
    }
}
I also find that this method of instantiating (or returning) a collection states my intent more clearly than something like:
CurrentOccupants = new List<Person();
The MSDN documentation for Enumerable.Empty states that it caches the returned empty sequence of type TResult - so using this consistently for the same types can give (probably negligible) performance or memory usage advantages.

This pattern also reduces the chances of null reference errors from being raised in calling code. As mentioned above, the calling code then doesn't need to go through the usual boiler-plate null check code on the returned collection. Naturally, this leads to cleaner code as the calling code can process the collection the same way if it has items or doesn't have items within it.

Sunday, 9 June 2013

C# Set Implementation (pre-.NET 3.5)

I was recently working on a .NET 3.0 project and found that this version of the framework didn't have any support for a mathematical Set collection. As of .NET 3.5 there is the System.Collections.Generic.HashSet implementation, however, I was working on a WinForms project and updating the framework on the client machines was out of scope for this piece of work.

I had some spare time available and thought it would be a good exercise to write a custom generic Set collection. The first step was to define an interface:

using System.Collections.Generic;

...

public interface ISet<T> : ICollection<T>
{
    void UnionWith(ISet<T> set);
    void IntersectWith(ISet<T> set);
}

By inheriting from ICollection, we get all of the generally useful collection-based methods included in the ISet interface (e.g. Add, Clear, Contains etc.). I just had two methods to add to those, these were the set union and set intersection operations.

The next step was the implementation of the set. To keep things simple, I opted for a list-based implementation. I used the adapter pattern to map the ISet interface to a list interface. Therefore, the internal representation of the Set was actually an instance of System.Collections.Generic.List. By using this approach, I could delegate a lot of the method logic to use the list method implementations (i.e. Clear, Contains, CopyTo and Remove). The only custom logic I needed to write was the Add method (to avoid adding items already within the set), UnionWith method, IntersectWith method, ToString method and the readonly indexer. The implementation is below:

/// <summary>
/// A list-based implementation of a mathematical set.
/// </summary>
public sealed class ListBasedSet<T> : ISet<T>
{
    private IList<T> _thisSet = new List<T>();

    /// <summary>
    /// Gets the number of elements contained in this set.
    /// </summary>
    public int Count { get { return _thisSet.Count; } }

    /// <summary>
    /// Gets a value indicating whether this set is readonly.
    /// </summary>
    public bool IsReadOnly { get { return false; } }

    /// <summary>
    /// Gets the item at the specified index in the set.
    /// </summary>
    /// <param name="i">
    /// Index of the item to retrieve from the set.
    /// </param>
    /// <returns>Item at the specified index</returns>
    public T this[int i] { get { return _thisSet[i]; } }

    /// <summary>
    /// Adds item into the set if this set does not already
    /// contain the item.
    /// </summary>
    /// <param name="item">Item to add to the set.</param>
    public void Add(T item)
    {
        if (!Contains(item))
            _thisSet.Add(item);
    }

    /// <summary>
    /// Clears the items from the set resulting in an empty set.
    /// </summary>
    public void Clear()
    {
        _thisSet.Clear();
    }

    /// <summary>
    /// Determines if the specified item is within the set.
    /// </summary>
    /// <param name="item">
    /// The object to locate in the set.
    /// </param>
    /// <returns>
    /// true if item is found in the set; false otherwise.
    /// </returns>
    public bool Contains(T item)
    {
        return _thisSet.Contains(item);
    }

    /// <summary>
    /// Copies the entire set to a one-dimensional array, 
    /// starting at the specified target index of the target 
    /// array.
    /// </summary>
    /// <param name="array">
    /// The one-dimensional array to copy to.
    /// </param>
    /// <param name="arrayIndex">
    /// The zero-based index in array at which copying begins.
    /// </param>
    public void CopyTo(T[] array, int arrayIndex)
    {
        _thisSet.CopyTo(array, arrayIndex);
    }

    /// <summary>
    /// Removes the specified item from the set.
    /// </summary>
    /// <param name="item">Item to remove.</param>
    /// <returns>
    /// true if item is successfully removed; otherwise, false. 
    /// This method also returns false if item was not found 
    /// in the set.
    /// </returns>
    public bool Remove(T item)
    {
        return _thisSet.Remove(item);
    }

    /// <summary>
    /// Returns an enumerator that iterates through the set.
    /// </summary>
    /// <returns>
    /// An IEnumerator object that can be used to iterate 
    /// through the set.
    /// </returns>
    public IEnumerator<T> GetEnumerator()
    {
        return _thisSet.GetEnumerator();
    }

    /// <summary>
    /// Returns an enumerator that iterates through the set.
    /// </summary>
    /// <returns>
    /// An IEnumerator object that can be used to iterate 
    /// through the set.
    /// </returns>
    System.Collections.IEnumerator 
        System.Collections.IEnumerable.GetEnumerator()
    {
        return _thisSet.GetEnumerator();
    }

    /// <summary>
    /// Modifies this set to contain all elements that are 
    /// present in itself, the specified collection, or both.
    /// </summary>
    /// <param name="otherSet">The set to union with.</param>
    public void UnionWith(ISet<T> otherSet)
    {
        foreach (var item in otherSet)
            Add(item);
    }

    /// <summary>
    /// Modifies this set to contain only the elements that are 
    /// present in it and in the specified collection.
    /// </summary>
    /// <param name="otherSet">The set to intersect with.</param>
    public void IntersectWith(ISet<T> otherSet)
    {
        var itemsToRemove = new List<T>();

        for (int i  = 0; i < Count; i++)
        {
            T item = this[i];

            if (!otherSet.Contains(item))
                itemsToRemove.Add(item);
        }

        foreach (var itemToRemove in itemsToRemove)
            Remove(itemToRemove);
    }

    /// <summary>
    /// Returns a string representation of this set
    /// </summary>
    /// <returns>A string representation of this set</returns>
    public override string ToString()
    {
        var setStringBuilder = new StringBuilder();
        setStringBuilder.Append("{");

        foreach (var item in _thisSet)
            setStringBuilder.Append(
                string.Format(" {0},", item));
            
        return string.Format("{0} }}", 
            setStringBuilder.ToString().TrimEnd(','));
    }
}

Example usage:
ISet<string> set = new ListBasedSet<string> 
    { "Mars", "Earth", "Pluto" };
ISet<string> otherSet = new ListBasedSet<string> 
    { "Jupiter", "Earth", "Pluto", "Venus" };
ISet<string> earthSet = new ListBasedSet<string> 
    { "Earth" };
ISet<string> emptySet = new ListBasedSet<string>();

set.UnionWith(otherSet);
Console.WriteLine("set UNION otherset = {0}", set);

Console.WriteLine("|set| (cardinality of set) = {0}", set.Count);

set.IntersectWith(earthSet);
Console.WriteLine("set INTERSECTION earthSet = {0}", set);

set.UnionWith(emptySet);
Console.WriteLine("set UNION emptySet = {0}", set);

set.IntersectWith(emptySet);
Console.WriteLine("set INTERSECTION emptySet = {0}", set);

You can download the source files for the ISet interface and the ListBasedSet class from here.

Sunday, 17 March 2013

Binding to PasswordBox in WPF using MVVM

I'm currently working on a Windows Presentation Foundation (WPF) client application that adheres to the Model View ViewModel (MVVM) design pattern. Having had a lot of experience with .NET WinForms, the WPF learning curve wasn't so steep. The main areas I initially concentrated on were getting to grips with XAML, then concepts such as data binding, commands, dependency properties and attached properties. It's the last of these that helped in resolving the problem I had with the PasswordBox control and view model binding.

In WPF, data binding enables you to hook a specific property in your data context (in my case, the view model) to a property on a user interface control. For example, the following XAML markup shows how the Text property on a TextBox can be bound to the FirstName property on the view model:
<TextBox Height="23" 
         Width="120" 
         Text="{Binding Path=FirstName, Mode=TwoWay}" />
As the Mode is set to TwoWay, any text changes by the user will result in the FirstName property being updated in the view model, likewise, any programmatic change to the FirstName view model property will result in the user interface being updated (provided that your view model implements the INotifyPropertyChanged interface and the setter of the FirstName property raises the OnPropertyChanged event). In my case, I had a PasswordBox control in my XAML markup that needed binding to a view model string property named Password. Initially I tried this in XAML:
<PasswordBox Name="userPasswordBox"
             Height="23" 
             Width="120"  
             Password="{Binding Path=Password, Mode=OneWay}" />
However, the Visual Studio XAML designer immediately underlined the 'Password="{Binding...' line and stated the error:
A 'Binding' cannot be set on the 'Password' property of type 'PasswordBox'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.
As the binding error message alludes to, it turns out that the Password property on the PasswordBox control is a standard .NET CLR property and this was a deliberate security-based design decision by Microsoft to prevent plain text passwords from sitting around in memory. In my case however, having the password sit in memory wasn't an issue.

Of course, if the application I was working on wasn't using MVVM, then I could easily have picked up the user entered password in the code-behind in a button click event handler (e.g. this.userPasswordBox.Password would return the plain password). But because the application was adhering to MVVM, the code-behind was pretty much empty (except for the usual constructor boilerplate code). Instead, all of the UI "events" were being handled by the view model via command objects exposed as public properties. This therefore made retrieving the password from the PasswordBox and assigning it to the view model Password property an annoyingly interesting problem!

After doing a bit of research on the web, I found a couple of solutions.

  • Pass the PasswordBox control to the view model: In this solution, the PasswordBox control itself is passed back to the view model via a command parameter (which is hooked up to the "OK" button). The method that handles the command then gets the PasswordBox instance via an object type parameter which can be cast back into a PasswordBox. You can then retrieve the password easily through the PasswordBox.Password property.
  • Use attached properties to enable binding: In this solution, attached properties (a special type of dependency property) are created, enabling you to use them on the PasswordBox control and bind to your view model property.

The first solution above works but I wasn't too happy with passing a UI component to my view model - it violates the MVVM design pattern principle of decoupling the view from the view model. I went for the second option as it enabled binding to the PasswordBox.Password property (albeit indirectly) and didn't violate the use of MVVM in the process.

To get this working, take a look at the static PasswordBoxAssistant class on Samuel Jack's interesting blog. The class defines the attached properties that you can then use in your XAML markup, in my case, it resulted in the following markup:
<PasswordBox Name="userPasswordBox"
             Height="23" 
             Width="120"  
             ap:PasswordBoxAssistant.BindPassword="true"
             ap:PasswordBoxAssistant.BoundPassword=
                "{Binding Path=Password, 
                  Mode=TwoWay, 
                  UpdateSourceTrigger=PropertyChanged}"
 
/>
As shown in the markup above, you'll need to import the namespace that the PasswordBoxAssistant class is defined in and add an alias to it (in my case "ap"). Having done that, it's finally just a case of using the attached properties to wire up the binding to your view model property.

Friday, 1 March 2013

The Generic Lazy Type

Lazy<T> is a monad type that was introduced in .NET 4 and provides an alternative mechanism for implementing lazy initialisation. Lazy initialisation is where you intentionally delay the creation of an object that is expensive to create.

You would typically want to use lazy initialisation in scenarios where the object (which is expensive to create) may or may not be used in the execution flow of your program. In this case, it makes sense to only initialise the object if it is required. One reliable place where you may have seen the lazy initialisation tactic being used is in an implementation of a singleton class - which will have a method or property that returns the singleton instance, for example:

public MySingletonClass GetInstance()
{
    if (_singleton == null)
        _singleton = new MySingletonClass();

    return _singleton;
}
The logic before the return statement is an example of lazy initialisation, where the singleton is only instantiated the first time GetInstance is called and never before it. Subsequent calls to GetInstance will then also return the same instance, hence we have an implementation of the singleton design pattern. In this particular case, we don't know if MySingletonClass is expensive to create, and we don't particularly care as we're using lazy initialisation to prevent multiple instances of MySingletonClass from being created.

If we now go back to the mainstream use for lazy initialisation, where we want to delay instantiation of expensive-to-create objects, you could adopt the pattern above where you conditionally instantiate an instance of an object. However, since .NET 4, you have an alternative option with the use of Lazy<T>. An instance of Lazy<T> wraps around your expensive-to-create object, you pass this instance around in your code and when ever the underlying expensive-to-create object is required, you can call the Value property on Lazy<T> which will instantiate the object and return it to you.

The following contrived example should make it more clear. Imagine you have a Customer class and an Order class. A single customer can have many orders, so we'll make use of composition and have the Customer class support a List of Order objects. The Customer class has one constructor that accepts a customer ID. Using the supplied ID, the constructor then goes and retrieves the orders for the customer from an order repository. Note that in reality your entity classes will usually be dumb and just support getter and setter properties and it'll be the responsibility of your data access layer/framework (like Entity Framework) to instantiate and populate your entities appropriately. Continuing with our contrived example, our initial attempt may therefore look like:

public class Order { }

public class Customer
{
    public int Id { get; private set; }
    public string Name { get; set; }
    public List<Order> Orders { get; set; }

    public Customer(int id)
    {
        Id = id;
        Name = "Ms Foo Bar";

        // Simulate getting lots of orders from an
        // order repository
        Orders = Enumerable
            .Repeat<Order>(new Order(), 200)
                .ToList();
    }

    public override string ToString()
    {
        return string.Format(
            "I'm customer with id {0}", Id);
    }
}
As the code indicates, it would be expensive to instantiate a Customer object if we didn't require the order information contained within it. This is where you would apply the concept of lazy initialisation. In this case, we'll make use of the Lazy<T> type. The following code shows how the Customer class would look if we lazily instantiate the Orders list using Lazy<T>.

public class Customer
{
    public int Id { get; private set; }
    public string Name { get; set; }
    public Lazy<List<Order>> Orders { get; set; }

    public Customer(int id)
    {
        Id = id;
        Name = "Ms Foo Bar";

        Orders = new Lazy<List<Order>>(() => {
            // Simulate getting lots of orders from an 
            // order repository 
            return Enumerable
                .Repeat<Order>(new Order(), 200)
                    .ToList();
            }
        );

        Debug.WriteLine(this);
    }

    public override string ToString()
    {
        return string.Format(
            "I'm customer with id {0}", Id);
    }
}
As you can see, the constructor of the Customer class instantiates an instance of Lazy<T> that wraps around the List of Order objects. The constructor of Lazy<T> is passed a lambda expression that expresses what needs to be returned when the list of orders is requested for (our expensive logic). Notice I've also put a call to Debug.WriteLine so you can observe the output of the following code and see how this behaves.

var customer = new Customer(1);
                       
Debug.WriteLine("Are orders instantiated? {0}", 
    customer.Orders.IsValueCreated);

// Ok, we now want the orders...
var ordersForCustomer = customer.Orders.Value;

Debug.WriteLine("Are orders instantiated? {0}", 
    customer.Orders.IsValueCreated);

Debug.WriteLine("Customer {0} has {1} order(s)", 
    customer.Id, ordersForCustomer.Count);
If you execute the code above using the updated Customer class, you'll find that instantiating a Customer object is no longer an expensive operation. The output you should see in your debug window is:

I'm customer with id 1
Are orders instantiated? False
Are orders instantiated? True
Customer 1 has 200 order(s)
Notice that when the Customer object was initialised, the runtime executed the constructor logic as expected (verifiable with the ToString output). We then check our Lazy objects IsValueCreated property to ensure it hasn't yet created an instance of the list and populated it. The property returned False as expected. On the next line, we explicitly call the Value property on the Orders property (our Lazy object) - this forces our lazy object to instantiate. We re-query the IsValueCreated property which now returns True and finally we output the order count to show that the orders have been successfully lazily-loaded.

Wednesday, 20 February 2013

Implementing the Chain of Responsibility Design Pattern

Earlier this week I made use of the Chain of Responsibility design pattern to solve a fairly straight-forward problem. I've always been careful when trying to apply design patterns, it's easy to get carried away and try to force a design pattern to a problem that doesn't really require it. In this case, I felt it was justified and hopefully you'll think the same!

The Context

I'll give some context to the problem before we go into exactly what the Chain of Responsibility pattern is. I was working on a HTTP service (built on ASP.NET Web API) which had an API controller action that accepted requests for some data stored in a persistent repository. My requirement was to inspect the incoming request object, and depending on certain characteristics of the request, log the request object data to zero or many different output locations. This is to enable reporting on the types of requests that the service receives. The output locations were disparate data stores such as an XML file, Excel file and SQL Server Database. The key point was that to log the request I had to inspect the content of the request, and depending on some criteria, log it to none or certain data stores. Furthermore, certain requests had to be ignored and therefore not logged.

Chain of Responsibility

When I read this requirement I knew immediately there was a design pattern for this type of problem. I had taken an Object-Oriented design pattern course at university around six years ago but couldn't quite remember the name of the pattern. After having a quick look on the GoF website, I eventually found it - Chain of Responsibility (CoR). CoR is a software design pattern that has been classified into the "behavioral" category of patterns - these are patterns that broadly deal with objects interacting with other objects. The idea is that you have multiple handler objects chained together just like a linked list data structure. An incoming request object is passed over to the first handler in the chain, the handler (depending on its "responsibility"), inspects the request and can either:
  1. Handle the request and not pass the request down the chain of handlers
  2. Handle the request but still pass the request down the chain of handlers
  3. Not handle the request and pass the request down the chain to the next handler
Note that before a handler sends the request object down the chain, it is also responsible for checking if it is actually linked to another handler. If a handler isn't linked to another handler, it is the last handler in the chain and therefore consumes the request.

Applying CoR to the Problem

In my case, the incoming data request to the API was my CoR request that required "handling" from a logging perspective. I implemented a separate concrete logging handler class for each of the concrete data stores (XML, Excel and SQL Server). Each logging handler inspected the request and logged the request if it matched the criteria for the handler before passing the request to the next handler. Therefore, in my case, the CoR handler behaviour corresponded to point two above.

The Implementation

Note that I've stripped down the code below (especially for each concrete handler) so that it is easier to see what's going on from a design pattern perspective.

The first step was to write an abstract base handler that defined the behaviour that each of my handlers will support. The HandlerBase class below is generic enough to be reused in any case where you require a CoR implemented. The single type parameter "TRequest" is the type of the object that will go through your chain (can be any .NET type).
public abstract class HandlerBase<TRequest>
{
    public HandlerBase<TRequest> Successor
    { 
        protected get; 
        set; 
    }

    public abstract void HandleRequest(TRequest request);
}
The HandlerBase class has one property, which allows users of a handler to set a successor to this handler (the next handler in the chain) and it has an abstract method that all derived classes will need to implement - HandleRequest. You will see further below how we use the Successor property when setting up our chain, and how each concrete handler (a class that derives from HandlerBase) uses the HandleRequest method on its successor to pass the request down the chain.

Next, I implemented each of my concrete handlers - that is, a handler for logging to an XML document, Excel document and SQL server.
public class LogRequestToXmlHandler : HandlerBase<ApiDataRequest>
{
    public override void HandleRequest(ApiDataRequest request)
    {
        if (request.Foo == Something && request.Bar == SomethingElse)
            // Log request to xml document

        // Pass on the request to the next handler, if any
        if (base.Successor != null)
            base.Successor.HandleRequest(request);
    }
}
Notice how the concrete handler LogRequestToXmlHandler derives from HandlerBase and passes the type of the object that is going through the chain - ApiDataRequest. Also notice that because we're inheriting from an abstract base class containing one abstract method - we're forced by the compiler to override the HandleRequest method. This method accepts one parameter, the request object. It is in this method that you will place any specific handling logic for the request object - I've added some pseudo-code to demonstrate this. The last couple of lines inspect the Successor property (inherited from the base class), if it isn't null - then we call the HandleRequest on it, thus passing our request down the chain. If Successor returns null, then the current handler is the last in the chain and we do nothing - effectively consuming the request. For completeness, the other handlers are below.
public class LogRequestToExcelHandler : HandlerBase<ApiDataRequest>
{
    public override void HandleRequest(ApiDataRequest request)
    {
        if (request.Foo == Something && request.Bar == SomethingElse)
            // Log request to excel document

        if (base.Successor != null)
            base.Successor.HandleRequest(request);
    }
}

public class LogRequestToDbHandler : HandlerBase<ApiDataRequest>
{
    public override void HandleRequest(ApiDataRequest request)
    {
        if (request.Foo == Something && request.Bar == SomethingElse)
            // Log request to database

        if (base.Successor != null)
            base.Successor.HandleRequest(request);
    }
}
Now that we have our handlers, the final step is to setup our chain so that it's ready to handle requests. The code below shows how the handlers are chained together.
HandlerBase<ApiDataRequest> logToXmlHandler
    = new LogRequestToXmlHandler();

HandlerBase<ApiDataRequest> logToExcelHandler
    = new LogRequestToExcelHandler();

HandlerBase<ApiDataRequest> logToDbHandler
    = new LogRequestToDbHandler();

logToXmlHandler.Successor = logToExcelHandler;
logToExcelHandler.Successor = logToDbHandler;
The first step above was to initialise each handler that will be going into the chain. We then use the Successor property to chain the three handlers together. The beauty of using this pattern is that you can chain however many handlers you want and even make the chain configurable so that it is setup at runtime depending on some settings in a config file.

Now, when a new request came through my API, it was a simple case of invoking the HandleRequest method on the first handler in the chain and passing the ApiDataRequest object through as a parameter. This sent the object down the chain, allowing each log handler to inspect it and decide whether to log it to their individual outputs.
logToXmlHandler.HandleRequest(request);
* Update *

One thing that I missed in this post and is worth mentioning is a scenario where you don't want each concrete handler to decide whether to pass the request on down the chain. In this case, the request would go to every handler in the chain regardless. One way to accomplish this is to update the HandlerBase class as follows:
public abstract class HandlerBase<TRequest>
{
    public HandlerBase<TRequest> Successor
    { 
        protected get; 
        set; 
    }

    public void HandleRequest(TRequest request)
    {
        Handle(request);

        if (Successor != null)
            Successor.HandleRequest(request);
    }

    protected abstract void Handle(TRequest request);
}
The updated HandlerBase now implements a public HandleRequest method which first delegates the handling logic to an abstract method (Handle) which will be overridden by a concrete handler. Once a request has been handled, a test is made to check if there is a successor and if there is, then the request is passed on. What this now means is that each concrete handler will implement just one method, Handle, and not need to worry about whether to pass the request on or not - that is done automatically in the HandleRequest method. An example concrete handler is below:
public class LogRequestToXmlHandler : HandlerBase<ApiDataRequest>
{
    protected override void Handle(ApiDataRequest request)
    {
        // Check request and log it, if required
    }
}

Friday, 10 February 2012

C# How To: Write a Fluent API

I've seen a number of API's now that utilise a "fluent" interface (e.g., Fluent NHibernate, Moq etc.). So far, I've had mixed feelings about it. If you're not familiar with what a fluent interface is, then Martin Fowler's post on this subject is a good starting point. By following a fluent design, you get some neat looking "client-side" code that is almost self-describing. The following example models a real-world person and exposes a fluent interface.

public class Person
{
    public string FirstName { get; private set; }
    public string Surname { get; private set; }

    private Person() { }

    public static Person New()
    {
        return new Person();
    }

    public Person SetFirstName(string firstName)
    {
        this.FirstName = firstName;
        return this;
    }

    public Person SetSurname(string surname)
    {
        this.Surname = surname;
        return this;
    }

    public override string ToString()
    {
        return string.Format(
            "I am {0} {1}",
                this.FirstName,
                    this.Surname);
    }
}
As the code snippet shows, each setter method in the Person class returns a reference to the "current" object (think context/state). This is important as it permits users of the class to chain method calls on the object, with each invocation returning an up-to-date state of the original object. For example, we can create an instance of Person and then set its state in one single C# statement:

var person = Person.New()
    .SetFirstName("Ravi")
        .SetSurname("Singh");
This looks neat and is very readable. Without a fluent interface, you may have code that looks somewhat like:

var person = new Person();
person.FirstName = "Ravi";
person.Surname = "Singh";
Of course, you could use the object initialiser syntax or pass the names through to an appropriate constructor, but that's not the point. The point is that you don't get the same readability or fluentness that you get using method chaining. If your methods are named properly, then using the fluent technique makes reading your code closer to reading a sentence in natural language.

I personally prefer the fluent version. Earlier in the post, I mentioned that I had a mixed feeling - this mainly stems from the fact that it becomes difficult to debug code that uses a fluent interface. For example, if you have a statement in which a number of method calls are chained on an object, it's difficult to see the intermediary values returned by each method unless you step into each method call. This can be a bit of a pain when debugging. Other than this one problem, I've enjoyed working with fluent-based API's and will strive to write classes in a more "fluent" way.