Brian Genisio's House of Bilz

  Home  |   Contact  |   Syndication    |   Login
  54 Posts | 0 Stories | 63 Comments | 0 Trackbacks

News

Locations of visitors to this page

Archives

Post Categories

Who am I?

Friday, June 19, 2009 #

More Adventures in MVVM Shout it kick it on DotNetKicks.com

imageA demo that I added to my MVVM talk is one that compares a “Ball of Mud” application with a componentized MVVM application with the exact same set of features.  I do this to contrast a messy, un-testable work of code to a cleanly separated, testable work.  The application I chose to write is a Twitter search application in WPF.  When you download the code, you will see two folders: “BallOfMud” and “MVVM”. 

The “Ball of Mud” app includes the entire app in a XAML file and a code-behind.  The code is incredibly dense… it does a TON of stuff, all in one page of code.  Unfortunately, is practically un-testable.  Even if you could test it, the code hits a live twitter.com.  Not the way you want to write tests.  This way of writing software works well for demos, but it certainly does not scale to real-life applications.

The MVVM example, on the other hand, is significantly broken up into components (4 layers).  There are 2 Views (TwitterSearchView and TweetView) with 2 corresponding ViewModels.  Then, there is a Model layer which is responsible for parsing data that comes from the Service layer into “Tweets”.  There is more code than the “Ball of Mud” example, but the code is testable, and modular.  You can swap out different services or models, if you wish.  In fact, in the Model layer, you will find a “CannedData” class that I use when I don’t have an internet connection when I give my presentation.  It just swaps in.  This example might feel like “overkill”, but as the application grows in scope, this architecture will scale exceptionally well.

Twitter Search “Ball of Mud” vs “MVVM”


Friday, June 12, 2009 #

More Adventures in MVVM

Shout it kick it on DotNetKicks.com

Yesterday, I gave my MVVM talk to the public for the first time in Flint, MI.  I will be in Southfield next week and Tennessee the week after that (CodeStock), giving the same talk.  Although I have some changes to make, I thought I would post what I presented last night.  I will probably work on a smaller example that I will also put up here when I am done with it.

The Demo

The demo is a front-end to a recipe database.  It should compile and run out of the box.  It was designed to work against www.eCuisine.com, but it requires you to sign up with them in order to get real data.  To get around that, I have stored some “canned” recipes in the service by default.  If you want to hook it up to use the real eCuisine.com service, simply register with them from www.eCuisine.com and add your email/client ID in the eCuisine.svc.cs file and uncomment the null for the service.  If you don’t do that, everything still works well enough for you to get the feel for the app.

The vast majority of the UI behavior exists in the View-Models and I show a few different approaches to getting View-Models hooked up to the views.

There is also a full suite of tests.  Be sure to check them out for ideas to how you might test your View-Models.

Demo Code

Powerpoint Slides


Friday, May 29, 2009 #

Shout it kick it on DotNetKicks.com

Continuing in my series of “Adventures in MVVM”, I want to talk about a few different approaches to working with List Boxes with the MVVM pattern.  What I am writing here is generally true of all controls that derive from Selector, including ListBox and ComboBox.  This example was developed in Silverlight, but the same concepts also apply to WPF.

The Problem

You have a list box in your view, and you want your ViewModel to do something when an item in the ListBox is selected. You want to do this without any code-behind, using the MVVM pattern.  There are three methods that I have come up with, and I will outline them here.  In this post, I will be using a VERY simple data class in my ListBox called Person with a First and Last name.  It is so simple, in fact, that I have chosen not to include the source for this class.

Method 1: Quick and Dirty SelectedItem binding

This method sets up a SelectedPerson property in the view model and does something when the property is changed. 

public class ViewModel : INotifyPropertyChanged
{
    public ObservableCollection<Person> People { get; private set; }

    private Person _selectedPerson = null;
    public Person SelectedPerson
    {
        get { return _selectedPerson; }
        set
        {
            _selectedPerson = value;
            OnPropertyChanged("SelectedPerson");    
            DoSomething(value);
        }
    }
    // ... rest of ViewModel
}
<ListBox ItemsSource="{Binding People}" SelectedItem="{Binding SelectedPerson, Mode=TwoWay}" />

Pros: This method is quick and simple to get going
Cons: You are introducing side effects in your property code.  If you are OK with this, then read no further.  If this bothers you the way it does for me, then lets look at our next option.

Method 2: Button Command

There are plenty of commanding libraries out there to choose from.  I will take advantage of the Prism commanding system (Microsoft.Practices.Composite.Presentation.Commands).  They have implemented bindable commands for ButtonBase.  The only problem: ListBox is not a ButtonBase.  To get around this, replace the ItemTemplate with a Button that has a template of textblock.

public class ViewModel : INotifyPropertyChanged
{
    public ViewModel()
    {
        PersonSelected = new DelegateCommand<Person>(DoSomething);
        // ... rest of constructor
    }

    public ObservableCollection<Person> People { get; private set; }
    public ICommand PersonSelected { get; private set; }

    // ... rest of ViewModel    
}
<ListBox ItemsSource="{Binding People}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Button Commands:Click.Command="{Binding PersonSelected, Source={StaticResource ViewModel}}" Commands:Click.CommandParameter="{Binding}" >
                <Button.Template>
                    <ControlTemplate>
                        <TextBlock Text="{Binding}" />
                    </ControlTemplate>
                </Button.Template>
            </Button>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Pros: The ViewModel is much more simple with no side effects. 
Cons: The XAML is ugly as sin.  It also changes the behavior of the ListBox in a subtle way.  Every time you select an item, the command fires, not just when it changes.  This is my LEAST favorite approach.  We can do better

Method 3: Bind Commands to the ListBox

The final mechanism is my favorite.  Even though Prism doesn’t give us the ability to bind commands to ListBoxes, we can extend their attached behavior infrastructure such that all ListBoxes and ComboBoxes (or anything that derives from Selector) can take advantage of it.  The ViewModel doesn’t change from “Method 2”, but the XAML does:

<ListBox ItemsSource="{Binding People}" Commands:Selected.Command="{Binding PersonSelected}" />

Pros: Best of both worlds.  Simple ViewModel.  Simple XAML
Cons: You have to write some extensions to the Prism infrastructure.  This code is boilerplate.  I have written some generics that can reduce the boilerplate code somewhat, but not completely, due to the static properties.

The Winner Is….

I like “Method 3” the best.  With a bit of some infrastructure code that you can tuck away, you get to bind the selected items to a command in any case.  It plays well, and it is easy to follow.

But wait… you want the Prism extensions?  Here they are:

public class SelectorSelectedCommandBehavior : CommandBehaviorBase<Selector>
{
    public SelectorSelectedCommandBehavior(Selector selectableObject)
        : base(selectableObject)
    {
        selectableObject.SelectionChanged += OnSelectionChanged;
    }

    void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        CommandParameter = TargetObject.SelectedItem;
        ExecuteCommand();
    }
}
public static class Selected
{
    private static readonly DependencyProperty SelectedCommandBehaviorProperty = DependencyProperty.RegisterAttached(
        "SelectedCommandBehavior",
        typeof(SelectorSelectedCommandBehavior),
        typeof(Selected),
        null);

    public static readonly DependencyProperty CommandProperty = DependencyProperty.RegisterAttached(
        "Command",
        typeof(ICommand),
        typeof(Selected),
        new PropertyMetadata(OnSetCommandCallback));

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Only works for selector")]
    public static void SetCommand(Selector selector, ICommand command)
    {
        selector.SetValue(CommandProperty, command);
    }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Only works for selector")]
    public static ICommand GetCommand(Selector selector)
    {
        return selector.GetValue(CommandProperty) as ICommand;
    }

    private static void OnSetCommandCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
    {
        var selector = dependencyObject as Selector;
        if (selector != null)
        {
            GetOrCreateBehavior(selector).Command = e.NewValue as ICommand;
        }
    }

    private static SelectorSelectedCommandBehavior GetOrCreateBehavior(Selector selector)
    {
        var behavior = selector.GetValue(SelectedCommandBehaviorProperty) as SelectorSelectedCommandBehavior;
        if (behavior == null)
        {
            behavior = new SelectorSelectedCommandBehavior(selector);
            selector.SetValue(SelectedCommandBehaviorProperty, behavior);
        }

        return behavior;
    }
}

Wednesday, May 27, 2009 #

Adventures in MVVM Shout it kick it on DotNetKicks.com

I have been spending a lot of time lately thinking about client architecture with Silverlight and to a lesser extent, WPF.  I tend to subscribe to the philosophy that when you make your code testable, you get a lot of other great qualities along with it.  I believe this so strongly that I go out of my way to architect my inherently untestable code in a way that I can, indeed, test it.

Since I have been writing most my code for the Silverlight platform in the past several months, and I wanted very much to write my code test-driven.  I used the Model-View-Presenter pattern (MVP) to implement my view as an interface.  The presenter would hand model objects over to the view and I would bind visual items in my view to the model items.  The presenter would then tell the IView what to do when any real logic came to play.  Over time, however, more and more logic started creeping into the code behind.  I had a lot of data converters to doing my dirty work, blending the code between the model and the view.  The problem is that anything within the IView implementation (aka code-behind) is not easily unit-testable.

organic

As I started to really understand how binding worked in the context of XAML, I found myself wanting to use binding against view-agnostic objects for testability.  Since the view didn’t know anything about the presenter, the only data to bind to was in the model.  Sadly, view-specific data started to creep into model items.  Where ThumbnailData (for instance) was only meta-information that came from my server, it began to gain properties such as Selected and Hidden.  Moreover, what “Selected” means to one part of the UI is different to another part of the UI.

This was not the direction I wanted to go.  In a fit of desperation, a colleague and I sat down and designed a pattern where we had a “ViewState” and a “ViewLogic” class.  “ViewState” was just a set of properties (model data and view properties) that implements INotifyPropertyChanged for the view to bind against and “ViewLogic” manipulated the “ViewState” to add the UI smarts.

The benefits were immediate and obvious.  We started seeing logic that was once in the code-behind move over to the “ViewLogic”.  We immediately received testing benefits.  We could write tests against the “ViewState” as if it were the actual UI.  We even started writing our new features with TDD.  Everything was great!

I was all ready to start blogging about it.  My colleague and I had come up with this fantastic pattern for making testable Silverlight UIs and I wanted to tell the world.  When doing some comparative reading I started seeing the “MVVM” term pop up here and there.  It didn’t take long for me to realize that what we had invented in a bubble was just a subtle variant of the Model-View-ViewModel pattern.  The ViewModel is really just our ViewLogic and ViewState combined into one single class.  It only solidified my belief that this pattern had legs.

Although I sensed some initial skepticism from my team-mates about using the pattern throughout the product, it didn’t take long for them to recognize how important the MVVM pattern would be to our project.  Since adoption our test coverage has skyrocketed with hundreds of useful tests.  The proof is in the pudding.  The vast majority of our bugs that come in have been one of two types of bugs: Missed features or improper binding – two things that the MVVM pattern can’t help prevent.

So, that is how I got so interested in the MVVM pattern.  Because it is relatively new, the community is still working out the best practices.  There is room for experimentation and that can be a lot of fun.  Lets solve the new problems.  Lets push the community in the right direction.  We are already hearing the buzz for Silverlight 3 to contain native support for MVVM (via Prism).  Lets keep this going… and lets have fun doing it!


Friday, May 22, 2009 #

Adventures in MVVM Shout it kick it on DotNetKicks.com

EDIT:

One of the things that I enjoy most about working with MVVM in Silverlight is how new it is.  When I say “new”, I mean that Silverlight doesn’t support the pattern very well out of the box, so the development community needs to step up and solve these problems.  Some solutions are better than others.  In this article, I solved a problem the best way I knew how.  I urge you to read Ward Bell’s comments to this article, and my responses.  After reflecting on it more, I concede that this is not the best way to implement a lightweight bindable command in SIlverlight.

Instead, I should have just read the Prism 2 source code to see how they implemented commands via attached behaviors.  I would have learned that that I learned attached behaviors wrong in the first place.  In Julian Dominguez’s blog post on the topic, he walks you through the thought process for attaching commands via behaviors.  Although this is not the final code that made it into Prism, it is very close.  I recommend reading it.

That being said, I will keep my original text in place.  I think that the thought process for how I got there is very useful for learning… at least I find it useful.  Then, be sure to read the comments, visit Julian’s blog and browse the Prism (CAL) source code.

One of the most important aspects of implementing the MVVM pattern in WPF and SIlverlight is the ability for the UI layer to bind directly to commands in the ViewModel.  The only problem with this:  commands were never implemented in Silverlight.  Even though I (and many others) have ranted about this, our voice has not been heard.  Even with the release of the Silverlight 3 beta, it seems as if we are still pining for commanding in Silverlight.

Many libraries have implemented commands in Silverlight, usually with some sort of static lookup table, mapping buttons to commands.  They include Prism, Caliburn, SilverlightFX and the MVVM toolkit.  It can feel like overkill to bring in these libraries just to get commanding.  There are plenty of good reasons to use these libraries – don’t get me wrong – but if you are just looking for bindable commands, there is an easier way.

This article will walk you through the process of creating a button with command properties.  This technique can be translated easily to any other control in order to achieve bindable commanding in Silverlight.

ICommand

The ICommand interface was the only thing that was included from the WPF commanding infrastructure within Silverlight.  The interface is extremely simple:

interface ICommand
{
    void Execute(object parameter);
    bool CanExecute(object parameter);
    event EventHandler CanExecuteChanged;
}

The requirements of any control that deals with ICommand are:

  1. Call Execute() when a trigger is hit
  2. Only call Execute() if CanExecute() returns true
  3. Allow a bindable parameter to be passed into Execute() and CanExecute()
  4. Disable the control when CanExecute() is false
  5. Refresh the enable/disable state of the control when the CanExecuteChanged event is raised

Implementing CommandButton

Lets start with requirements 1 and 2:

public class CommandButton : Button
{
    public CommandButton()
    {
        Click += (sender, e) =>
        {
            if (Command != null && Command.CanExecute(null))
                Command.Execute(null);
        };
    }

    public static DependencyProperty CommandProperty =
        DependencyProperty.Register("Command",
                                    typeof(ICommand), typeof(CommandButton),
                                    new PropertyMetadata(null));

    public ICommand Command
    {
        get { return GetValue(CommandProperty) as ICommand; }
        set { SetValue(CommandProperty, value); }
    }
}

With this, you can bind a command in the ViewModel to the view:

public class ViewModel : INotifyPropertyChanged
{
    public ViewModel()
    {
        MyCommand = new DelegateCommand<object>(DoSomething);
    }

    private void DoSomething(object obj)
    {
        // Do what you want
    }

    public ICommand MyCommand { get; private set; }

   // The rest of your ViewModel
}

This XAML creates a CommandButton in place of a Button:

<local:CommandButton Content="Click Me" Command="{Binding MyCommand}" />

Adding Parameters

Implementing feature 3 is trivial. Add the CommandParameter property and pass it in to Execute() and CanExecute()

public class CommandButton : Button
{
    public CommandButton()
    {
        Click += (sender, e) =>
        {
            if (Command != null && Command.CanExecute(CommandParameter))
                Command.Execute(CommandParameter);
        };
    }

    // Everything else from initial Implementation
	
    public static DependencyProperty CommandParameterProperty =
        DependencyProperty.Register("CommandParameter",
                                    typeof(object), typeof(CommandButton),
                                    new PropertyMetadata(null));

    public object CommandParameter
    {
        get { return GetValue(CommandParameterProperty); }
        set { SetValue(CommandParameterProperty, value); }
    }
}

With that, you can add parameters to the XAML:

<local:CommandButton Content="Click Me" Command="{Binding MyCommand}" CommandParameter="MyParameter" />

Hooking IsEnabled to CanExecute()

Things get a bit more complicated when implementing requirements 4 and 5, but it is still pretty straight-forward.  I start by registering an event handler for when the Command property changes (CommandChanged).  This event handler hooks the CanExecuteChanged event and handles the event by setting the IsEnabled flag to the value of CanExecute().  It then proceeds to initialize the value of IsEnabled since we know the answer at this time.

The final class:

public class CommandButton : Button
{
    public CommandButton()
    {
        Click += (sender, e) =>
        {
            if (Command != null && Command.CanExecute(CommandParameter))
                Command.Execute(CommandParameter);
        };
    }

    public static DependencyProperty CommandProperty =
        DependencyProperty.Register("Command",
                                    typeof(ICommand), typeof(CommandButton),
                                    new PropertyMetadata(null, CommandChanged));

    private static void CommandChanged(DependencyObject source, DependencyPropertyChangedEventArgs args)
    {
        var button = source as CommandButton;
        if (button == null) return;

        button.RegisterCommand(args.OldValue as ICommand, args.NewValue as ICommand);            
    }

    private void RegisterCommand(ICommand oldCommand, ICommand newCommand)
    {
        if (oldCommand != null)
            oldCommand.CanExecuteChanged -= HandleCanExecuteChanged;

        if (newCommand != null)
            newCommand.CanExecuteChanged += HandleCanExecuteChanged;

        HandleCanExecuteChanged(newCommand, EventArgs.Empty);
    }

    private void HandleCanExecuteChanged(object sender, EventArgs args)
    {
        if (Command != null)
            IsEnabled = Command.CanExecute(CommandParameter);
    }

    public ICommand Command
    {
        get { return GetValue(CommandProperty) as ICommand; }
        set { SetValue(CommandProperty, value); }
    }

    public static DependencyProperty CommandParameterProperty =
        DependencyProperty.Register("CommandParameter",
                                    typeof(object), typeof(CommandButton),
                                    new PropertyMetadata(null));

    public object CommandParameter
    {
        get { return GetValue(CommandParameterProperty); }
        set { SetValue(CommandParameterProperty, value); }
    }
}

Summary

This method for hooking commands to buttons has one drawback in my opinion:  It requires you to put a CommandButton in your XAML instead of a vanilla Button.  This, of course, means that other controls that inherit from Button such as Checkbox and RadioButton do not get this behavior (you have to implement this pattern for them).  Still, this approach makes it very easy to add commands to any control you wish; even in WPF.  In a future post, I will discuss a similar approach for binding a command to a ComboBox (or ListBox) selection changed event.


This post is intended to be a high-level post intended to index all of my “Adventures in MVVM” posts.  I will be traveling the region this summer giving talks on the MVVM pattern and these posts are part of me working through the details of the MVVM pattern.  These posts will not include the “What”.  There are several good articles on the web that do that already.  Instead, I will be taking a deeper dive into MVVM and writing on the “How” and “Why” of the MVVM pattern.


Tuesday, May 19, 2009 #

I have been busy lining up opportunities to talk about Model-View-ViewModel (MVVM) in the context of WPF and SIlverlight.  The good news is that I have some great gigs lined up this summer:

In addition to that, I will be attending the Ann Arbor Give Camp July 17-19.

In preparation for my MVVM talks, I will be honing my knowledge of the pattern by blogging here, so check back often if you are interested in MVVM!


Saturday, May 02, 2009 #

Shout it kick it on DotNetKicks.com

No matter what your opinion is about singletons (I favor against them in most cases), it is important to understand what you can do when you encounter code that is dependent upon them.  Unfortunately, I have come across a lot of code that has abused singletons in a way that makes other code less testable.  My examples here are in C#, but this technique can work in any language.  In some languages, these techniques are easier due to their dynamic capabilities.

I am going to choose a singleton example I have seen in books when the “Singleton Pattern is described – a logger.  Have you seen code like this before?

public class Log
{
    private Log()
    {
        // Set up a way to write to a logging service somewhere
    }

    private static readonly Log theOnlyOne = new Log();
    public static Log Instance
    {
        get { return theOnlyOne; }
    }

    private void WriteToLog(string errorLevel, string category, string message)
    {
        // Write to the logging service
    }

    public void Error(string category, string message)
    {
        WriteToLog("ERROR", category, message);
    }

    public void Warning(string category, string message)
    {
        WriteToLog("WARNING", category, message);
    }

    public void Information(string category, string message)
    {
        WriteToLog("INFORMATION", category, message);
    }
}
public class SomeClass
{
    public int Calculate()
    {
        Log.Instance.Information("client", "Doing something...");

        // do calculations
        return 0;
    }
}

Disclaimer: I am not addressing concurrency issues at all in this post.  These techniques work with or without concurrency code.  For the sake of brevity, I left it out.

Of course, if I want to unit-test Calculate(), I have a problem.  Every time I run my test(s), the event log will get written to.  This could be a file, a database, or even a web service.  This type of side-effect behavior is a pretty bad way to be writing my unit tests.  To make matters worse, what happens if I want to validate that Calculate() logged a message appropriately?  Do I read the file, database or web service to validate? 

What I really want here is a test double… but how do I get it in there?  I can:

  1. Re-factor out the singleton
  2. Re-factor the consumer
  3. Put a shim in it
  4. Wrap it

In C#, the first three methods require that the Log be modified.  It either needs to implement an interface, or the methods need to be made virtual.  I prefer to use an interface so that none of the base implementation makes it into the test.  The fourth method can be used in a case where the ability to modify the singleton is prohibited for one reason or another.

The interface for all four strategies is:

public interface ILog
{
    void Error(string category, string message);
    void Warning(string category, string message);
    void Information(string category, string message);
}

Re-Factor Out the Singleton

It is often the case that a singleton does not need to be a singleton. It was just a lazy design decision made a long time ago, but it doesn’t need to be this way.  In fact, when it makes sense to do so, this is my preferred way to deal with singletons.  In this case, I have to ask: why does it need to be a singleton?  There might be a reason, but in most cases, I can just modify the class to not be a singleton anymore and modify the consumer to accept the ILog object via dependency injection:

public class Log : ILog
{
    public Log()
    {
        // Set up a way to write to a logging service somewhere
    }

    // Remove the static instance
    // Remove the Instance getter

    // Everything else the same
}
public class SomeClass
{
    private readonly ILog log;
    public SomeClass(ILog log)
    {
        this.log = log;
    }

    public SomeClass() : this(new Log())
    {}

    public int Calculate()
    {
        log.Information("client", "Doing something...");
        
        // do calculations
        return 0;
    }
}

Now the test is easy to write.  I can create a test double of any type I want here, just as long as it implements ILog.

[TestFixture]
public class SomeClassTests
{
    [Test]
    public void Test_That_Calculate_Returns_Zero()
    {
        var test = new SomeClass(GetLoggerStub());

        Assert.That(test.Calculate(), Is.EqualTo(0));
    }
}

That is the best way to work with a singleton, in my opinion.  Unfortunately, it is not always that easy.  Maybe it is too much of a refactoring to take the “single” out of the singleton.  Whatever the reason, I need the singleton to stay as a singleton.  The next question:  Do I need my consumer to treat it like a singleton?

Re-factor the Consumer

In this case, the Log class will stay as a singleton, but it is modified slightly to implement ILog:

public class Log : ILog
{
    // Everything else the same
}

Next, the consumer is modified in a similar way to pass the ILog object in via dependency injection:

public class SomeClass
{
    private readonly Func<ILog> log;
    public SomeClass(Func<ILog> log)
    {
        this.log = log;   
    }

    public SomeClass() : this(() => Log.Instance)
    { }

    public int Calculate()
    {
        log().Information("client", "Doing something...");

        // do calculations
        return 0;
    }
}

Notice the difference in the way that SomeClass is instantiated now.  Instead of passing a log instance, I pass a function that gets the log instance.  That is because caching a reference to a singleton is a bad idea – the singleton instance has the right to change out from under me.  Instead, the default behavior of SomeClass will ask for the singleton instance every time, but it is no longer required to use the singleton implementation of ILog.  Instead, I can test this in a very similar way (the difference here is subtle, but important… notice that I pass GetLoggerStub as a function, not the result of GetLoggerStub()):

[TestFixture]
public class SomeClassTests
{
    [Test]
    public void Test_That_Calculate_Returns_Zero()
    {
        var test = new SomeClass(GetLoggerStub);

        Assert.That(test.Calculate(), Is.EqualTo(0));
    }
}

Unfortunately, this is not always easy either.  The class I am refactoring may already have a complicated set of constructors.  It may be the case that these are public objects that I don’t want to change right now.  There are several reasons why this might not work for me.  The next option: Leave the Log class as a singleton, but don’t modify the consumer in any way.  Instead, put a shim in the singleton.

Put a Shim in it

This tends to be the technique I use most often, because it creates the least amount of friction when it comes to refactoring the classes for testability.  After all, if there are no tests to validate that I don’t break anything in my re-factoring, I don’t want to make drastic changes.  The consumer doesn’t need to change or know about the changes to the Log class.  It kind of breaks up the singleton pattern a bit (there can be TWO instances!), but all is fair in love and testing, right?  The modified:

public class Log : ILog
{
    private Log()
    {
        // Set up a way to write to a logging service somewhere
    }

    private static ILog theOnlyOne;
    private static ILog testOverride;

    public static ILog Instance
    {
        get
        {
            if (testOverride != null)
                return testOverride;

            if(theOnlyOne == null)
                theOnlyOne = new Log();

            return theOnlyOne;
        }
    }

    public static void OverrideInstanceForTesting(ILog log)
    {
        testOverride = log;
    }
  
    // Everything else the same
}

Again, I don’t have to modify my consumer class, but my test fixture has to do a bit more work:

public class SomeClassTests
{
    [SetUp]
    public virtual void SetUp()
    {
        Log.OverrideInstanceForTesting(GetLoggerStub());
    }

    [TearDown]
    public virtual void TearDown()
    {
        Log.OverrideInstanceForTesting(null);
    }

    [Test]
    public void Test_That_Calculate_Returns_Zero()
    {
        var test = new SomeClass();

        Assert.That(test.Calculate(), Is.EqualTo(0));
    }
}

This option might not be the available either.  If the singleton is a publically consumed service and I can’t modify it for some reason (I don’t own it, for instance), then I can wrap it.

Wrap it

This is a technique I use when Microsoft has given me a static class or singleton that I don’t want a direct dependency to, but they also didn’t give me an interface to substitute in either.  I just create my own interface that looks a lot like the singleton and wrap it!

public class LogWrapper : ILog
{
    public void Error(string category, string message)
    {
        Log.Instance.Error(category, message);
    }

    public void Warning(string category, string message)
    {
        Log.Instance.Warning(category, message);
    }

    public void Information(string category, string message)
    {
        Log.Instance.Information(category, message);
    }
}

With that, I can use the same modification to the consumer as in “Re-Factor Out the Singleton”.  The test also looks the same as “Re-Factor Out the Singleton”.

In Summary

There are other ways to deal with this problem.  I could use TypeMock Islolator to replace the singleton implementation with a new one.  I have even seen some suggestions that you can use a post-compiler code injection library to replace the singleton implementation.  These, to me, are cheating.  They get around a problem that you have in your system: tight coupling.  I much prefer the strategies mentioned in this post for dealing with singletons because they allow you to make baby steps towards loose coupling.  Over time, these re-factorings add up and push you in the direction of having testable code.


Sunday, April 26, 2009 #

Shout it kick it on DotNetKicks.com

I have just released an early version of Html Utilties for Silverlight on CodePlex.  This article will explain the whats and hows of this library.

Who is this library for?

The primary target for this library is someone who:

  1. Develops software in Silverlight
  2. Uses the Html DOM libraries in Silverlight

What problem does this library solve?

In the first version of this library, it is all about testability.  Lets say I have a (very simple) method I want to test.  The code looks like this:

public class HtmlGenerator
{
    public static HtmlElement CreateImage(string url)
    {
        var img = HtmlPage.Document.CreateElement("img");
        img.SetAttribute("src", url);
        return img;
    }
}

Trying to write a test for this becomes very difficult.  There are two problems here:

  1. HtmlPage is static, and testing CreateImage with this static is not a unit test.  It relies on the browser.
  2. Unless your tests are executing in the browser, there is no browser to fall back on.  HtmlPage.Document fails with an exception that the HtmlPage is not enabled.

The test I WANT to write includes the ability to stub out the call to CreateElement and verify that the source was set.  Using NUnit and Moq, it would look something like this:

// JUST AN EXAMPLE OF WHAT I WANT TO DO.  SEE ACTUAL TEST FURTHER DOWN
[Test]
public void Test_Create_Image_Creates_Element_And_Sets_Src()
{
    var mockImage = new Mock<HtmlElement>();
    HtmlPage_Document.Setup(doc => doc.CreateElement("img"))
        .Returns(mockImage.Object);

    var newImage = TableGenerator.CreateImage("AbcDef.png");

    Assert.That(newImage, Is.EqualTo(mockImage.Object));
    mockImage.Verify(img => img.SetAttribute("src", "AbcDef.png"));
}

I can’t do anything like this because the HtmlPage is static and there are no interfaces on any of the classes in the DOM.

This is a very contrived example for the purpose of illustration, but I have had to use this approach in many cases from loading new windows, to inserting data into the DOM.

What does this library do?

This library wraps all of the HtmlPage classes with wrappers that implement interfaces.  For instance, HtmlPage is wrapped around a proxy that implements IHtmlPage.  HtmlElement has a proxy wrapper that implements IHtmlElement.  By using this approach, you can substitute anything you want in the Html DOM when you test.  This may be any test object that implements the interfaces.  I prefer to use Moq, but there are several other approaches to testing now that the system has interfaces to replace.

How do I use the library?

In an attempt to make the migration as simple as possible, any code that uses HtmlPage.* is just replaced with Html.Page.* (notice the dot after Html). 

So, in the example above, the code would look like this now:

public class HtmlGenerator
{
    public static IHtmlElement CreateImage(string url)
    {
        var img = Html.Page.Document.CreateElement("img");
        img.SetAttribute("src", url);
        return img;
    }
}
Notice that the only differences between these two methods are:
  1. The return type is IHtmlElement instead of HtmlElement
  2. HtmlPage.Document is replaced with Html.Page.Document

Next, my entire test fixture looks like this:

public class HtmlGeneratorTests
{
    private MockHtml _mockHtml;

    [SetUp]
    public virtual void SetUp()
    {
        _mockHtml = new MockHtml();
    }

    [TearDown]
    public virtual void TearDown()
    {
        _mockHtml.TearDown();
    }

    [Test]
    public void Test_Create_Image_Creates_Element_And_Sets_Src()
    {
        var mockImage = new Mock<IHtmlElement>();
        _mockHtml.Document.Setup(doc => doc.CreateElement("img"))
            .Returns(mockImage.Object);

        var newImage = HtmlGenerator.CreateImage("AbcDef.png");

        Assert.That(newImage, Is.EqualTo(mockImage.Object));
        mockImage.Verify(img => img.SetAttribute("src", "AbcDef.png"));
    }
}

You may be noticing that this test references a class named MockHtml.  This is a class that implements the HtmlPage system using Moq, but you can do this in any way. 

The most important thing to notice in this class is that we inject the IHtmlPage into the system using Html.SetHtmlPageForTesting() when we construct the object, and we set it back to null when we are complete.  This is required so that when Html.Page is called, it calls your test implementation of IHtmlPage instead of the wrapper around the actual browser.

public class MockHtml
{
    public Mock<IHtmlPage> Page { get; private set; }
    public Mock<IBrowserInformation> BrowserInformation { get; private set; }
    public Mock<IHtmlDocment> Document { get; private set; }
    public Mock<IHtmlWindow> Window { get; private set; }

    public MockHtml()
    {
        Page = new Mock<IHtmlPage>();
        BrowserInformation = new Mock<IBrowserInformation>();
        Document = new Mock<IHtmlDocment>();
        Window = new Mock<IHtmlWindow>();

        Page.SetupGet(page => page.BrowserInformation).Returns(BrowserInformation.Object);
        Page.SetupGet(page => page.Document).Returns(Document.Object);
        Page.SetupGet(page => page.Window).Returns(Window.Object);

        Html.SetHtmlPageForTesting(Page.Object);
    }

    public void TearDown()
    {
        Html.SetHtmlPageForTesting(null);
    }
}

How do I get it?

Version 0.1 has been released on CodePlex.  The source code is available on this site, along with the release DLL.  The Source project is broken into 4 projects: The HtmlUtilities project, a Silverlight test, a Web Site to host the Silverlight test, and a set of unit tests, showing how to mock out everything you would want to do with the library.

Future plans

I have some thoughts for where this library should go.  I want to aim towards a very easy to use API for manipulating the DOM through Silverlight.  My original thought was that the roadmap might look something like:

0.1 -- Wrappers around existing objects
0.2 -- Extensions to existing objects (HtmlLink, HtmlImage, HtmlDiv, etc)
0.3 -- Helper utilities for doing more complex actions on the HTML
0.4 -- Cross-browser issues abstracted away?
0.5 -- Anything else??
1.0 -- World domination???

At least, in the next few versions, it would be nice to be able to do something like create a table using code that is much more clear than what it takes now.  Possibly something that looks more like:

Html.New<Table>("Border=1",
    Html.New<THead>(
        Html.New<TR>(Html.New<TH>("Header 1"), Html.New<TH>("Header 2")),
    Html.New<TBody>(
        Html.New<TR>(Html.New<TD>("Data 1.1"), Html.New<TD>("Data 1.2")),
        Html.New<TR>(Html.New<TD>("Data 2.1"), Html.New<TD>("Data 2.2")))));

The Table type would have static properties on it instead of the more awkward way of doing it now. I dunno... I'm just playing at this poing. Would that be useful?


Sunday, March 29, 2009 #

Shout it

Much like my previous post about what I use for testing in Silverlight, I was recently asked on Twitter for my ReSharper NUnit templates.  I am posting them here if anyone finds them useful.

Basically, I write a LOT of tests every day.  These templates allow me to write tests faster.

New Test File Template

This file template adds a new “Test” target when you say tell Visual Studio to create a new file from template.  It populates your file with the correct namespaces and decorations to get you started.

Coding Templates

These are shortcuts that create new tests, setups, teardowns or assertions.  You just type the shortcut, hit tab, and the method or lines are created for you with your mouse cursor in the next place to type.  The shortcuts are:

  • test – Create a new [Test] method
  • setup – Create a [SetUp] method
  • teardown – Create a new [TearDown] method
  • ise – Assert that condition is equal to value
  • ist – Assert that condition is true
  • isf – Assert that condition is false
  • isn – Assert that condition is null
  • isnn – Assert that condition is not null

Download my ReSharper 4 NUnit templates.