Using Unity to make Singleton-ness an implementation detail

The most common, canonical use of the Singleton pattern irritates me. Every time I see it, I think, “The singleton-ness of a class is an implementation detail, and shouldn’t leak out through that class’s interface.” Yet, that’s what it always does.

In the usual implementation, someone decides that some new class they’ve written is so resource critical, or so standalone, or so useful that they can have only one instance of that class and that instance has to be visible everywhere. Ignoring the intricacies of threading and so on, a Singleton usually looks exactly like this:

   1: public class MyImportantResource

   2: {

   3:     private static MyImportantResource instance;

   4:  

   5:     private MyImportantResource()

   6:     {

   7:         // ...

   8:     }

   9:  

  10:     public static MyImportantResource Instance()

  11:     {

  12:         if (instance == null) instance = new MyImportantResource();

  13:         return instance;

  14:     }

  15: }

And it gets used everywhere like this:

   1: public class Consumer

   2:     {

   3:         public Consumer()

   4:         {

   5:             var importantResource = MyImportantResource.Instance();

   6:             importantResource.FooTheBar();

   7:         }

   8:     }

Now what happens when I decide I want two of these? Or I decide that I want to let people create as many of these resources as possible? Or, even more commonly, what happens when I want my Consumer class to use a mocked out version of MyImportantResource? I’m scre^h^h^h^hin trouble.

The trouble comes from the fact that Consumer is reaching out into the ether and grabbing the resource it needs on its own. It isn’t giving me, the developer, control over what type of ImportantResource to use or where the ImportantResource is coming from. The Inversion of Control principle is being violated by having the class gather its own resources rather than having its creator decide and pass resources to it.

My typical solution

What I typically have been telling people is that it is OK to have a singleton, treat it as a singleton, and love the singleton pattern… within reason. At the point in your code where you’re creating all your objects and wiring them up, you should feel perfectly free to use singletons. But no layer beneath that should have any knowledge of the singleton-ness of a class. Grab that singleton and pass it into whoever needs it, preferably as an interface, and you’ve restored order and testability to your system by again returning to the Inversion of Control principle.

My DI solution

Dependency Inversion containers solve this problem for you automatically. I’ve been using Unity lately, and I’ve grown to really like it. One of the things I really like about it, and I’m sure all DI containers have this property, is that I can register a type with the container and tell it that I only want it to create a single instance of this type and pass it around whenever someone asks for that type. Bam! I have a singleton again, but I’ve completely separated the singleton-ness of the class from its singleton-like usage. Major win. Here is the code that lets me do that.

First, the interface over the important resource:

   1: public interface IImportantResource

   2: {

   3:     void FooTheBar();

   4: }

Now the changes in the MyImportantResource class to bring it back to being a regular class. Note that all mention of singleton-ness is gone from this class. Its just a plain, old class again, which is how we like it.

   1: public class MyImportantResource : IImportantResource

   2: {

   3:     public MyImportantResource()

   4:     {

   5:         // ...

   6:     }

   7:  

   8:     public void FooTheBar()

   9:     {

  10:         throw new NotImplementedException();

  11:     }

  12: }

Next, the changes in the Consumer class that promote the loose coupling encouraged by Inversion of Control, by injecting an IImportantResource at construction:

   1: public class Consumer

   2: {

   3:     public Consumer(IImportantResource importantResource)

   4:     {

   5:         importantResource.FooTheBar();

   6:     }

   7: }

And finally, the object construction code I can write:

   1: public static class Configurator

   2: {

   3:     private static IUnityContainer container;

   4:  

   5:     public static void Main(string[] args)

   6:     {

   7:         container = new UnityContainer();

   8:  

   9:         container.RegisterType<IImportantResource, MyImportantResource>(new ContainerControlledLifetimeManager());

  10:  

  11:         Consumer consumer = container.Resolve<Consumer>();

  12:     }

  13: }

The interesting bit of code here is on line 9, where I register MyImportantResource. I’m telling the container that whenever someone asks for an IImportantResource, it should give them a MyImportantResource object, and that it should give it the same instance every time (that what the new ContainerControlledLifetimeManager()) says. I’ve magically turned my MyImportantResource into a singleton class without polluting the code of that class with statics and instance methods.

Conclusion

Operationally nothing has changed. Assuming people always go to the container for their object instances, MyImportantResource is still a singleton. I will only have one instance of it, it is still accessible from a single place. Should I ever decide to allow 4 instances of it, I can create my own lifetime manager class that will create up to four instances and manage them for me. But now all of my classes are just that, classes. The design decision of how many instances of the resource is separated from the operation of the resource, which allows the two different design issues to evolve separately. And I’ve applied Dependency Inversion to the Consumer class, which allows it to have mock versions of the resource injected to enable testing scenarios that were more difficult when it was using the singleton.

— bab

Test Driving a WPF application using MVVM and TDD

This is a preview of the material I’m going to be presenting at the St. Louis Day of Dot Net in a couple weeks.

Introduction

For those of you who are reading this blog for the first time, I’m pretty much the St. Louis Agile Zealot. Long hair, flowing robes… you get the picture 🙂 I’ve been advocating Agile and XP in St. Louis since around 2000, through speaking at various user groups and local conferences, teaching at local companies, giving talks in the park, dropping leaflets from airplanes, and so on. I live Agile in my day job at Asynchrony Solutions, where I lead their Agile training and mentoring group. I am totally sold on Test Driven Development as the best way for me to write my code, and I’ve been occasionally known to share that opinion with others.

As far as WPF experience goes, I’m still pretty new in my learning curve.  I’ve been playing with a project on my own for a few months, trying new things, reading, and experimenting. When I first started out, I completely wrote a Winforms app in WPF. I used a full-on MVP/MVC architecture, had my button click methods in my window classes, etc. A complete mess… Then I started reading about MVVM and that sparked something inside me that realized that this finally made sense. This was something that gave me a lot of the advantages of the MVP-like architectures, such as being able to test my UI without actually running the UI, but without the overhead of wiring all that junk up myself.

What follows are the lessons I’ve learned in the process of rethinking my original app and in writing this sample app for my talk.

The Application

My daughter plays select softball for one of the organizations here in St. Louis. They have a web site that lists all their stats throughout the year, and I thought it would be fun to mimic that site as a desktop app. The application would list all the girls’ total stats on the front page and give you the ability to drill down into detailed stats for each game on subsequent pages. For fun, I wanted to be able to add stats for new games, and add and delete players. With that set of features, it seemed that I’d be able to drive out a lot of interesting opportunities to change around the design to let me write the code in a TDD manner.

Here is the main page of the application, in all its glory. Remember that I am but a poor developer, with a developer’s eye for style 🙂

image

The display of stats isn’t complete yet, but it was enough to validate that my data binding was working. Let’s look at what it took to get this far…

Note: If you want to skip the setup stuff and get right to the parts where behavior is added, jump ahead to Step 3.

Our Roadmap

As a quick review, before we dive in, here is an overview of the MVVM design pattern and the players involved.

MVVM Architecture

The View represents the surface that the user interacts with. It is the WPF code, the UI, and XAML… all that stuff that users see and that is hard to test in an automated fashion. Our goal is to take as much logic out of there as possible, to allow us to have the highest amount of confidence and the greatest amount of test coverage that we can achieve.

Next to the View is the ViewModel. The ViewModel represents the entire set of data and behavior contained in the View. It has properties to expose all the different pieces of data that the View will  need to display, and it exposes another set of properties for all the behavior that the View will need to invoke.

The View and ViewModel are tied together in two separate, but very similar, ways. Through Data Binding, data travels between the View and ViewModel automatically. WPF, through the wonders of its internal magic, keeps consistent the data shown in the View and the data held in the ViewModel. There is a bit of work that we have to do to ensure this happens, but it mostly all automatic. The Commands are representations of the behavior that users invoke through the View. Individual commands are exposed through properties on the ViewModel and tied to controls on the View. When the user presses a button, for example, the command attached to that button fires and something happens. You can think of Commands as little controllers, focused on a specific topic, whose responsibility it is to respond to a user action in a particular manner by coordinating the response to that action between the View and ViewModel.

Our goal here is to put all logic about the View into the ViewModel. The View should be very thin and code-less, and the Commands should be thin shims that merely provide an execution conduit between the gesture being made and the behavior being invoked in the ViewModel. Code in the View or in Commands should be looked up with suspicion, with an eye towards trying to move it into someplace more testable. Sometimes you can move that code, and sometimes its entirely appropriate where it is, but the question should always be asked.

Step 1 – Modify the template to support TDD

When you create a WPF application using the Visual Studio New Project dialog, you get the framework of an empty application. There is no code anywhere, other than an InitializeComponent() call here and there. Most of the interesting behavior, at this point, takes place through XAML – things like instantiating the Application object, creating the main window and causing it to display, and other basic things like that. While this works, and works fine for the empty application, we’re going to need more control over how this initiation process occurs, for reasons we’ll discuss later in this post or a subsequent one.

So, to control the initial creation, there are a few changes we need to make. The first step is to put ourselves in control of when and where the main window is created. As time goes on, there are aspects of this creation process that we’re going to want to control, like wiring together other objects, so we’ll need full control over the how windows and controls are born.

App.xaml

When first created, App.xaml looks like this:

   1: <Application x:Class="WpfApplication1.App"

   2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

   3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

   4:     StartupUri="Window1.xaml">

   5:     <Application.Resources>

   6:          

   7:     </Application.Resources>

   8: </Application>

The StartupUri attribute of the Application element is what causes the class defined in Window1.xaml to be instantiated. We want to prevent this from happening until we’re ready for it, so we have to take this out. We’ll still need to create this window, however, so we’ll need to arrange for another way to create objects as the system is starting. It turns out that WPF exposes and event that is perfect for this initialization, the Startup event. By providing a handler for the Startup event, we can have a place to put all our initialization code.

App.xaml now looks like this:

   1: <Application x:Class="WpfApplication1.App"

   2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

   3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

   4:     Startup="Application_Startup">

   5:     <Application.Resources>

   6:  

   7:     </Application.Resources>

   8: </Application>

Now we have to add some code into the App.xaml.cs file to create the objects we need and to wire them together. Please note that I’m not writing tests for this code, because this is configuration code, not business logic. I view logic such as this the same way I view a Main method, and I tend not to test Main’s. It is where objects are created and wired together and then told to go on their merry way. This is not meant to be reusable code and should be just simple declarations of objects and assignments of variables. If I manage to screw up Main, the application isn’t going to work anyhow, and I’m pretty sure I’ll know it 🙂

   1: using System.Windows;

   2:  

   3: namespace WpfApplication1

   4: {

   5:     public partial class App : Application

   6:     {

   7:         private void Application_Startup(object sender, StartupEventArgs e)

   8:         {

   9:             Current.MainWindow = new MainWindow();

  10:             Current.MainWindow.Show();

  11:         }

  12:     }

  13: }

The final step is to rename the template-provided window name of Window1 to MainWindow and make sure I instantiate it with the proper class name in the Application_Startup method, the handler for the Startup event. Once that is done, you can start the project, and an empty window should appear.

image

 One more change…

Before going further, I’d like to introduce Unity into the codebase. Unity is the dependency injection library from Microsoft, and I’ve found it to be very useful in my WPF applications. Here is the previous code after injecting Unity (injecting Unity – HA! I kill myself).

   1: using System.Windows;

   2: using Microsoft.Practices.Unity;

   3:  

   4: namespace WpfApplication1

   5: {

   6:     public partial class App : Application

   7:     {

   8:         private readonly IUnityContainer container = new UnityContainer();

   9:  

  10:         private void Application_Startup(object sender, StartupEventArgs e)

  11:         {

  12:             container.RegisterType<MainWindow>(new ContainerControlledLifetimeManager());

  13:  

  14:             Current.MainWindow = container.Resolve<MainWindow>();

  15:             Current.MainWindow.Show();

  16:         }

  17:     }

  18: }

Briefly, the point of this code is to register a type, MainWindow, with the Unity container, and then use the container to instantiate the MainWindow object as the application’s main window. The reason I introduced Unity is to separate myself from the semantics of object creation. Unity will take care of instantiating any objects I ask for, as well as any objects that the class being created needs. Its just a way of relieving myself of having to worry about constructor signatures, basically.

Step 2 – Adding the initial content

Its time to fill in the empty window with some content. We’ll avoid adding any behavior yet, we just want to see something. The strategy that we’re going to use is to keep the MainWindow class as the one window in our application, and we’ll swap in and out different pieces of content to show in it. In my projects I’ve found this pattern to be useful, because it lets me layer content to mimic a workflow in the application, and have the content always show up in the same place, be the same size, and not take extra work to manage.

So our goal now is to set the MainWindow’s content to be the initial view we want to show people when they first open the application. The design for this looks like this:

DesignWithTeamStatControlAndViewModel

And the implementation is easy, too.

First, I create my user control, TeamStatsControl:

image

At the same time, I create a ResourceDictionary to hold styles that I’ll be using around the app and merged that dictionary into my UserControl.Resources section. I created a menu, a somewhat attractive header, and a couple of buttons. There’s no behavior in it yet, but that’s coming shortly.

Now, for the fun part, let’s make the simple change to make the content show up in the MainWindow. Since we’re creating a new object, our TeamStatControl, we have to make a few simple changes in App.Application_Startup. We need to register the user control with Unity so that it can create it as needed, and then resolve an instance of it as the Content property of the MainWindow. Once that is done, WPF takes care of making it appear in the window.

   1: private void Application_Startup(object sender, StartupEventArgs e)

   2: {

   3:     container.RegisterType<MainWindow>(new ContainerControlledLifetimeManager());

   4:     container.RegisterType<TeamStatControl>(new ContainerControlledLifetimeManager());

   5:  

   6:     Current.MainWindow = container.Resolve<MainWindow>();

   7:     Current.MainWindow.Content = container.Resolve<TeamStatControl>();

   8:     Current.MainWindow.Show();

   9: }

And, by the way, I also changed the Width and Height properties in MainWindow to be 600 and 1000 respectively so that the entire user control would be visible.

Step 3 – Adding behavior

Now that the shell is in place, we can add the behavior that we want. First, lets add the basic behavior of exiting the application in an orderly way. We want to be sure to do this in a way that all the code that we write is testable, and that is going to require a bit of extra work over and above just writing the simplest code. This is the price one pays when writing code using TDD, but the extra effort pays off in systems that work.

Let’s start by writing our first test. This test will be a test of the Command object, which is the object that the view will interact with. An underlying force of the MVVM pattern is that the ViewModel encapsulates the visible data and behavior of the View. And the Command object acts as the conduit through which the gestures of the user are translated into tangible actions in the ViewModel. Here is a sequence diagram showing this behavior:

CommandExecutionSequenceDiagram

Clicking the button causes the Command.Execute method to fire, which calls a method in the ViewModel. That method does the real work of this system, with the calls coming before it just part of the plumbing to cause things to happen.

So lets write a test to show that the above sequence is what will actually happen – that calling the Execute method of some Command object will invoke some sort of behavior that causes the application to exit.

Our first test:

   1: namespace ViewModelFixtures

   2: {

   3:     public class ApplicationExitBehaviorFixture

   4:     {

   5:         [Fact]

   6:         public void ApplicationExitingBehaviorInvokedWhenExecuteCalled()

   7:         {

   8:             var exiter = new Mock<IApplicationExitAdapter>();

   9:             ApplicationExitCommand command = new ApplicationExitCommand(exiter.Object);

  10:             exiter.Setup(e => e.ExitApplication()).Verifiable();

  11:  

  12:             command.Execute(null);

  13:  

  14:             exiter.Verify(e => e.ExitApplication());

  15:         }

  16:     }

  17: }

For those of you unfamiliar with the tools used in this test, I’m using Moq as my mocking framework and xUnit for my tests. These are my two favorite tools for TDD as of now, and I highly recommend both of them.

Beginning on line 7, defines the behavior of the system when my ApplicationExitCommand.Execute method is called. I’m defining the interface that the command is going to talk to, IApplicationExitAdapter, and I’m doing this in total and complete ignorance of what class is ever going to implement that interface (OK, I’m lying – its going to be my view model, but let’s keep that our secret for now).

And the code that we write to get this test to compile:

   1: namespace ViewModels

   2: {

   3:     public interface IApplicationExitAdapter

   4:     {

   5:         void ExitApplication();

   6:     }

   7: }

   1: namespace ViewModels

   2: {

   3:     public class ApplicationExitCommand : ICommand

   4:     {

   5:         public ApplicationExitCommand(IApplicationExitAdapter exitAdapter)

   6:         {

   7:             throw new NotImplementedException();

   8:         }

   9:  

  10:         public void Execute(object o)

  11:         {

  12:             throw new NotImplementedException();

  13:         }

  14:  

  15:         public bool CanExecute(object parameter)

  16:         {

  17:             throw new NotImplementedException();

  18:         }

  19:  

  20:         public event EventHandler CanExecuteChanged;

  21:     }

  22: }

Strictly speaking, I went a little further than I had to here, choosing to implement ICommand, but all commands that are hooked through a View as we’re discussing need to implement this interface (or one of a couple of others that are more advanced), so I just went ahead and did it.

Short Aside – Projects and Solution Structure

Before we go further, we should discuss the projects I’ve chosen to use in this solution, and why they were chosen. I have one project that holds the view and a separate project that holds the view models. I intentionally kept the Views and ViewModels separate to enforce the direction of the relationship between them. The Application class and the other WPF controls need to have access to the ViewModels, if only to create them and assign them to DataContexts. ViewModels, however, should be 100% ignorant of their views. The simplest way to enforce this constraint is to put all view model code into another assembly, which is what I’ve done.

Now its a simple matter of implementing the code to make the test pass:

   1: public class ApplicationExitCommand : ICommand

   2: {

   3:     private readonly IApplicationExitAdapter exitAdapter;

   4:  

   5:     public ApplicationExitCommand(IApplicationExitAdapter exitAdapter)

   6:     {

   7:         this.exitAdapter = exitAdapter;

   8:     }

   9:  

  10:     public void Execute(object o)

  11:     {

  12:         exitAdapter.ExitApplication();

  13:     }

  14:  

  15:     public bool CanExecute(object parameter)

  16:     {

  17:         return true;

  18:     }

  19:  

  20:     public event EventHandler CanExecuteChanged

  21:     {

  22:         add { CommandManager.RequerySuggested += value; }

  23:         remove { CommandManager.RequerySuggested -= value; }

  24:     }

  25: }

I also went ahead and added some boilerplate code into the CanExecute and CanExecuteChanged method and event inside this class. This boilerplate code is what you start with every time you write a command. You can think of this as creating a command using a code template inside Visual Studio.

At this point, the command should be invoking the behavior that we want, as seen in this diagram:

ApplicationExitCommandSequenceDiagram

Now that the behavior is being called inside the IApplicationExitAdapter, we’ll need to make the giant leap and assume that it is, indeed, our view model class that is going to be implementing that interface. This only make sense, since the Command is invoking behavior on some class that represents the behavior of the View, and the class that represents a View’s behavior is that View’s ViewModel. Q.E.D. Once we’ve crossed that intellectual chasm, we’ll go ahead and implement the functionality inside the view model.

For that, we write this test:

   1: [Fact] 

   2: public void ApplicationControllerInvokedWhenViewModelExitApplicationCalled()

   3: {

   4:     var applicationController = new Mock<IApplicationController>();

   5:     TeamStatControlViewModel viewModel = new TeamStatControlViewModel(applicationController.Object);

   6:     applicationController.Setup(ac => ac.ExitApplication()).Verifiable();

   7:  

   8:     viewModel.ExitApplication();

   9:  

  10:     applicationController.Verify(ac => ac.ExitApplication());

  11: }

This test causes us to make a few design decisions. First, we’ve discovered an interface called IApplicationController that is going to be responsible for controlling application-wide behavior, which would certainly include things like exiting at the appropriate time. We’re also creating the view model class, TeamStatControlViewModel, since we have to add behavior directly to it now. And finally, we’ve discovered that the view model needs to have a reference to the IApplicationController interface, to allow it to invoke functionality through that interfacee. This leads us to creating a constructor for the view model through which we can inject the interface at creation.

Here is the resulting code. First, the simple IApplicationController interface:

   1: namespace ViewModels

   2: {

   3:     public interface IApplicationController

   4:     {

   5:         void ExitApplication();

   6:     }

   7: }

and now the TeamStatControlViewModel:

   1: namespace ViewModels

   2: {

   3:     public class TeamStatControlViewModel : IApplicationExitAdapter

   4:     {

   5:         private readonly IApplicationController applicationController;

   6:  

   7:         public TeamStatControlViewModel(IApplicationController applicationController)

   8:         {

   9:             this.applicationController = applicationController;

  10:         }

  11:  

  12:         public void ExitApplication()

  13:         {

  14:             applicationController.ExitApplication();

  15:         }

  16:     }

  17: }

That’s just enough code to make that test pass, so we’re momentarily happy. However, our system isn’t going to work yet, because we haven’t found anyone to implement the IApplicationController interface. That’s our next major decision.

ClassDiagramExceptForFinalClass

I’m going to choose to put this interface onto the App class, at least for now, since it seems to be the one place in our application that has knowledge of the entire application. It may turn out later that we need to move this responsibility somewhere else, but we’ll leave it here for now.

We’ll go ahead and make the easy changes to App.xaml.cs, which consist of making it implement IApplicationController and writing the ExitApplication method, which simply calls Current.Shutdown().

   1: public partial class App : Application, IApplicationController

   2: {

   3:     private readonly IUnityContainer container = new UnityContainer();

   4:  

   5:     private void Application_Startup(object sender, StartupEventArgs e) {...}

   6:  

   7:     public void ExitApplication()

   8:     {

   9:         Current.Shutdown();

  10:     }

  11: }

The important point to note is that the IApplicationController interface lives in the ViewModel assembly, even though it is being implemented by the App class in the main WPF assembly. This means that the main WPF application project has to have a reference to the ViewModel project, which is the direction we want the dependencies to flow. By moving the ViewModel classes and interfaces into an a project separate from the view classes, we’re enforcing our dependency management design as we described earlier.

This now leaves us with this for a design:

ClassDiagramFinal

So we’re in the home stretch now. We have all our code built – what is lacking now are the few scattered bits and pieces needed to wire this whole thing together. There are several of these pieces, and we’ll look at them one at a time.

Let’s start with the object creation changes needed in App.Application_Startup. Over these last few changes, we’ve created a new interface for the App class, so we need to tell Unity that when I ask for an instance of an IApplicationController, it should pass back a reference to the App class. You can see this code on line 3 below. We also created a TeamStatControlViewModel, which we tell Unity about on line 5.

   1: private void Application_Startup(object sender, StartupEventArgs e)

   2: {

   3:     container.RegisterInstance<IApplicationController>(this);

   4:  

   5:     container.RegisterType<TeamStatControlViewModel>(new ContainerControlledLifetimeManager());

   6:     container.RegisterType<TeamStatControl>(new ContainerControlledLifetimeManager());

   7:  

   8:     container.RegisterType<MainWindow>(new ContainerControlledLifetimeManager());

   9:     

  10:     Current.MainWindow = container.Resolve<MainWindow>();

  11:     Current.MainWindow.Content = container.Resolve<TeamStatControl>();

  12:     Current.MainWindow.Show();

  13: }

Next, we know that TeamStatControlViewModel is going to be the DataContext for the TeamStatViewModel, so let’s make that happen in code. The easiest way is to change the constructor for the TeamStatControl to take the view model and assign it to be its DataContext in its constructor. The really cool part of this is that we don’t have to make any changes in App.ApplicationStartup based on this constructor changing. Unity will just build all the dependent objects for us and call whatever constructors it can find, and it all just works.

   1: public TeamStatControl(TeamStatControlViewModel viewModel)

   2: {

   3:     DataContext = viewModel;

   4:     InitializeComponent();

   5: }

Now that we have the objects built and wired up, we need to do the data binding to put the commands into the controls on the interface. The first place to do this is in TeamStatControl, where we define the Quit button. We need to assign an instance of the ApplicationExitCommand to the Command attribute of the button. Here is the XAML code that will do this for the Quit button:

   1: <Button Command="{Binding ApplicationExit}" Grid.Column="1" Content="Quit" HorizontalAlignment="Left" Style="{StaticResource NormalButton}"/>

We do this by creating a binding to the ApplicationExit property of our data context, the TeamStatControlViewModel. The view is now expecting the view model to expose a property called ApplicationExit, of type ICommand, through which it can get the command. We don’t have that property right now, so lets write a test that makes us create it.

   1: [Fact]

   2: public void ViewModelExposesApplicationExitCommandAsICommand()

   3: {

   4:     TeamStatControlViewModel viewModel = new TeamStatControlViewModel(null);

   5:  

   6:     Assert.IsAssignableFrom<ApplicationExitCommand>(viewModel.ApplicationExit);

   7: }

This test says that we can get an ICommand from the view model and the ICommand we get is actually an ApplicationExitCommand, which is what we need. We just need to implement that through creating a simple auto-property in the view model. That satisfies what we need for the binding we defined in the XAML. Now, we construct the command in the constructor of the TeamStatControlViewModel class and pass an instance of the view model to the constructor of its command to wire that up, and we’re set!

   1: public TeamStatControlViewModel(IApplicationController applicationController)

   2: {

   3:     this.applicationController = applicationController;

   4:     ApplicationExit = new ApplicationExitCommand(this);

   5: }

   6:  

After all this, running the application and clicking the Quit button should cause the app to vanish silently, slipping into the night, never to be seen again. Whew!

A Bonus

Now that all this hard work is done, we can also  hook this same logic to the menu button. If we go into the XAML and find the line where we define the menu item, we just set its Command attribute to be a binding to ApplicationExit as well, and now it works, too.

Conclusion

As I said at the beginning, this blog entry, and the couple more that will follow this week, will form the basis for my St. Louis Day of Dot Net talk on this same subject. I’d appreciate any and all feedback on this article, especially including things that weren’t clear, design  leaps I made without a clear reason, and alternative ways to do the same things I did.

You can find the complete project for this on my website. You may need to install Unity to get the solution to compile.

Thanks for reading, and I hope it helps!

 

— bab

I’m thinking of an example…

I’m writing an example for a workshop on estimation in an agile context, and I’m considering using the idea of preparing a multi-course meal. I think I like this because it is entirely non-technical, so I can give it to developers, customers, QA, or anyone else without regard to previous technical knowledge. I also like it because there are obvious tie-ins to concepts like freshness, inventory, rapid delivery, and so on. That is as close to the real-world considerations of a software project I can think of while keeping it approachable for everyone.

So, here goes:

I have 100 guests showing up in 6 hours for an end of project celebration. This is the entire project team and their families. They did a great job on their last delivery, so we want to reward them with a feast. The menu is top secret, but we want it to surprise and delight them as much as possible. Here is the schedule:

12:00PM – 1:00PM – Guests start arriving. I need hors d’oeuvres ready and passed around through the crowd as they gather.

1:00PM-2:00PM – Salad and appetizer course served

3:00PM-4:00PM – Lunch

5:00PM-5:30PM – Dessert and Coffee

That gives us 4 different courses to serve. I have a kitchen filled with supplies, everything you might need. The pantry is well stocked, tons of pots and pans, spices, herbs, three ovens and stoves, and anything else you might need. I just need you and your team of world-class chefs to create something for me and my guests.

I’d like to have 4 or 5 different hors d’oeuvres, 3 different kinds of salads, 2 kinds of appetizers. Lunch should be a buffet of 3 meats, 2 pasta dishes, 3 vegetables, and a rice dish. I’d like 3 different desserts, one decadently sweet, one fruit dish, and a big cake.

So, off you go. Give me a selection of great food at each of these times. Bear in mind that things can go wrong, like ovens not working, menus changed, schedules shortening, so you’ll have to constantly keep your eye on time and delivering the best culinary value for the given effort.

So, how did that sound? I intend to mix things up by adding vegetarian dishes to the lunch menu, an oven going out, changing the schedule, running out of something… Basically doing whatever it takes to have them adapt, replan, and go forward.

Does this sound close enough to a real software project to be useful? Does the exercise sound like anything that would teach estimation and prioritization? Any sort of feedback would be greatly appreciated.

bab


Handling interactions between ViewModel classes

I’ve been puzzling over what seemed to be an insurmountable problem lately. It seemed that the guys who came up with the MVVM design pattern totally missed the boat on anything more than a simple, single-page app. It couldn’t be me, since I’m a SuperGenius (TM).

Well, OK, it did turn out to be me. Once I stopped flailing about in WPF-land and actually thought about the problem, it became easy.

The Problem

What I was trying to do seemed pretty simple, and I couldn’t figure out how to make it work, which is why I was sure it was them and not me – how wrong I would be…

Basically, I had an app with multiple views. In one view, I was doing something that caused some data to be updated. I wanted to show the updated data in another view. Since the two views were using two different ViewModels, I couldn’t figure out how data binding by itself could solve the problem. Then it came to me – the two different ViewModels were sharing the idea of the data they were both showing, and data is supposed to live in the Model layer. Duh!

Once this epiphany drilled its way through my head, I figured out how to solve the problem (Note – I’m 100% new to WPF, so there is every chance there is an easier way to do this. If you know it, please let me know!)

The Solution

The key to this was to make both my ViewModels implement INotifyPropertyChanged to hook them up to propagate changes to and from their Views. Then I created an event in the Model that would be raised whenever the underlying data they were sharing was changed. My model looked like this:

   1:     public class Model
   2:      {
   3:          private String modelValue;
   4:   
   5:          public delegate void ModelChangedEvent(object sender, ModelChangedEventArgs e);
   6:          public event ModelChangedEvent ModelChanged;
   7:          public void SetValue(string newValue)
   8:          {
   9:              modelValue = newValue;
  10:              if(ModelChanged != null)
  11:              {
  12:                  ModelChanged(this, new ModelChangedEventArgs {OldValue = modelValue, NewValue = newValue});
  13:              }
  14:          }
  15:      }

And I had my target ViewModel listen for this event. In the event handler for the ModelChangedEvent, the ViewModel used the newValue to set the value it needed to show on the View, which caused the PropertyChanged event to be raised, and everything worked like a champ. Here is the target ViewModel:

   1:      public class ReflectedViewModel : INotifyPropertyChanged
   2:      {
   3:          private string reflectedValue;
   4:          private Model model;
   5:          public event PropertyChangedEventHandler PropertyChanged;
   6:   
   7:          public Model Model
   8:          {
   9:              get { return model; }
  10:              set
  11:              {
  12:                  if(model != null) throw new InvalidOperationException("Attempted to set model more than once.");
  13:                  model = value;
  14:                  model.ModelChanged += model_ModelChanged;
  15:              }
  16:          }
  17:   
  18:          void model_ModelChanged(object sender, ModelChangedEventArgs e)
  19:          {
  20:              ReflectedValue = e.NewValue;
  21:          }
  22:   
  23:          public String ReflectedValue
  24:          {
  25:              get { return reflectedValue; }
  26:              set
  27:              {
  28:                  if(value.Equals(reflectedValue) == false)
  29:                  {
  30:                      reflectedValue = value;
  31:                      if(PropertyChanged != null)
  32:                      {
  33:                          PropertyChanged(this, new PropertyChangedEventArgs("ReflectedValue"));
  34:                      }
  35:                  }
  36:              }
  37:          }
  38:      }

You can download the entire example from here.

Conclusion

This was not a hard problem to solve, once I stopped and actually thought about it. I got so wrapped up in the new framework and toys (WPF/XAML) that I forgot about everything else I knew for a bit 🙂

As usual, any and all comments appreciated. Comments telling me about easier and more idiomatically correct ways of writing this are 100% welcomed!

— bab

Agile in 6 words

My good friend, Matt Philip, wrote an interesting blog entry the other day about Six-Word Memoirs By Writers Famous and Obscure. I thought it might be interesting to write about the agile methods, their values, and their practices, following a similar style. So here goes, my own take on Six-Word Memoirs on Agile Values, People, and Activities…

Agile: Business plans, developers do, people thrive
Agile: Don’t want “resources”, give me people!
Agile: Project success comes from working together
Agile: Engine converting features to software daily
Agile: Solve biggest problem. Lather, rinse, repeat

QA: Hey, I made the team!!! Yea, QA!!!
QA: Building it right the first time
QA: Equal parts developer, tester, and customer
QA: The glue that holds ‘em together
QA: Helping customers define what they want

Scrum Master: Equal parts facilitator, friend, and psychologist
Scrum Master: My job is to listen carefully
Scrum Master: If I do it, you don’t!
Scrum Master: Fixing problems is not the solution

Customer: Content is mine, method is yours
Customer: I chart the course to success
Customer: You let me worry about that
Customer: Word of mouth, my best tool
Customer: Don’t read specs, ask me questions

Developer: I eat user stories for breakfast
Developer: I trust my customer and team
Developer: It feels good to be valued
Developer: Method is mine, content is yours
Developer: Best architectures owned by whole team
Developer: Ivory tower architects need not apply
Developer: Red, green, refactor. Lather, rinse, repeat.
Developer: Its more fun done in pairs

Delivery: Running, tested features – what really counts
Delivery: Scope is negotiable, quality is not
Delivery: Not over, under promising, just delivering
Delivery: Reliably delighting the customer every week

I could do more, but lets leave it there. Any more?

—bab

Obvious comment of the day – TDD makes Pair Programming easier

A fairly obvious observation hit me today…

If you are trying to pair program without also doing test driven development, when do you change roles? When doing TDD with Pairing, there is a rhythm to when the roles switch – see Micro Pairing. But if you’re not doing TDD, the person typing is frequently lost in solving a fairly large problem, they are balancing a bunch of things in their heads, and they have to finish a big thought before they could possibly swap the keyboard with their pair. So, while the typer is solving these big problems, what does the other person do? Just sit there? It just seems pretty painful…

I’m sure its not impossible, but it sure seems like TDD is a near necessity for Pair Programming.

Thoughts?

— bab

Continuing the Growing up Geek Meme

I’ve been tagged by Brad Wilson to tell a bit about my geek childhood. Like most of you, I certainly had one 🙂

My earliest geek memories starts with watching Star Trek back in about 1972. It was Return of the Archons – the one where the zombies in robes wander around talking about “Being of the Body”. I remember being totally and completely fascinated by it, and being hooked on science fiction from that point on. That led me to finding the Heinlein juveniles, like Space Cadet, The Rolling Stones, Double Star, Citizen of the Galaxy and so on. I can honestly say that Heinlein’s attitudes about politics, religion, and life, as well as Spock’s general logical demeanor, were a huge influence on me back when I was somewhere near 10 or a bit younger.

A few years later, I learned about amateur radio somehow. I think it was a year or two before we moved from Des Moines, IA to St. Louis, MO. I remember buying The Amateur Radio Handbook, a highly technical book that was years too old for me — I must have been about 8 at the time. I wanted to get my ham license right then, immediately, so I started studying. Of course, electronic theory was a big part of the test, so I had to learn about stuff like Ohm’s Law. The only problem was that it kind of required algebra, and at 9, I hadn’t really learned that yet. So my 4th grade teachers, Mrs. Clark and Ms. Dean, sent me to the 5th grade teacher for algebra tutoring. I did finally get my license a couple of years later, after moving to St. Louis. A couple helpful hams in town taught me the last few bits I needed, including letting me practice Morse Code, and I passed my General test when I was 10 or 11. I was now WD0FDG 🙂 Over the next couple of years, I studied for the highest class license, the Amateur Extra, taking the test a couple of times, only to fail. On my last attempt, I missed the last two questions on the exam, pushing me over the limit by 1. Had I passed, I would have been one of the 10 youngest Extra class licensees in the country at that point 🙁

After that, I spent a lot of my time reading Heinlein’s more mature novels, talking on my radio, playing with electronics, playing violin, and other exciting activities for an early-teen boy.

I eventually did find sports and girls a few years later, but some things never change… I haven’t been on the radio on years, but I know I’ll get back to it some day. I did pick up amateur astronomy a few years ago, a similarly geeky habit, still read Heinlein religiously, if you’ll excuse the expression, and still watch Star Trek in all its forms. And now there is this computer thing that seems to eat up so much of my time 🙂

Well, that is the geek story of me. Hmmm, I guess I should tag a couple of other folks now… How about Cory Foy, Ade Miller, and Michael Feathers

(I’ll update this post with a picture of me as a kid once I get home!)

— bab

A Story Splitting Story

This is a true story from a true client I’m working with . The names and details have been changed to protect the innocent…

Story splitting

Several of us were attending a pre-sprint planning meeting yesterday, trying to flesh out the user stories that the product owner was planning to bring to sprint planning in a few days. They are still pretty early in their agile adoption as well as their technology adoption, so there are lots of questions floating around about process and tools.

A story came up in the meeting that described the interaction that a user would take when visiting the site the first time, more specifically around the user agreement presented to them the first time they logged into the site. The story was something like:

“As a user, I want to be to able to accept the user agreement so that I can access my content”

The details of this story included a specific workflow to follow if the user didn’t agree, including errors to show them, and a need to refrain from showing the user agreement again after agreeing to it the first time.

Conversation around this story went on for a while, mainly focusing around the second part, how to handle remembering what the user did the last time they visited the site. There were technical details about where this information needed to be stored that hadn’t been agreed to yet, and team spun a bit around this issue.

The suggestion was made to split the story into two. The first story would be the same as the first, “As a user, I want to be able to accept the user agreement so that I can access my content”, and it included all the acceptance criteria other than the remembering part. The second story would be “As a previously logged in user, I will not be presented with the user agreement, since I had already agreed to it”, which picked up the remembering part.

By splitting the story in this way, they were able to work out the important part for the customer, which was the user agreement workflow, and defer the technical issues over where to store the agreement status until they could discuss the issue more.

Moral of the story

When discussing a story, if there is contention about how part of it is done, it is sometimes possible to split the story so that the understood part is separated from the not understood part, allowing progress to be made. In this case, we knew how to write the workflow, but not how to prevent the user from seeing the agreement each time. We split the story at that particular edge, which allowed the team to build something useful, and to defer what they didn’t know yet until they knew more about it later.

— bab

What do you think of this code?

I recently finished 6 weeks of coding for a client, and it was heaven! I actually got a chance to code every day, for 6 solid weeks. It was a chance for me to learn C# 3.0, and a chance to work on testing things that are hard to test. It was great!

Out of the work, came several interesting observations and coding techniques, all rooted in C# 3.0. Since no one at work has any experience with these new idioms I “invented”, “discovered”, or just “copied”, I’d love to get some reader feedback. I’ll start with this one trick I tried, and follow on with more as the mood strikes me over time.

Trick 1: Using extension methods and a marker interface in place of implementation inheritance

I had an instance of code duplication in two parallel hierarchies of classes, and I wanted to find a way to share the code. One option would be to use inheritance, factoring out another base class above BaseResponse and BaseRequest. This is where methods common to requests and responses could both live. Using inheritance as a way to reuse code in a single inheritance language is a pretty heavyweight thing to do. I’d rather find a way to use delegation, since that preserves the SRP in my class hierarchy. Instead, I decided to try an extension method, and just use that method where I needed it. To avoid polluting Object with unnecessary methods, however, I came up with the idea of using a marker interface on the classes I wanted to have these extension methods, limiting the scope where these extra methods were visible. (No idea if anyone else has done this yet or not)

ClassDiagram1

For each request and response class, in the two parallel  hierarchies, my client requirements made it necessary to add an XmlRoot attribute to tell the XmlSerializer that this object was the root of an XML document and to specify the runtime name of this element. To let me get the runtime name of each request and response object, for auditing and logging purposes, both hierarchies had a CommandName property, containing the exact same code. This was the code in question that I was trying to share.

As a simple exercise, I created an extension method to deal with this:

    internal static class SssMessageExtensionMethods
    {
        public static string GetCommandNameFromXmlRootAttribute(this object message)
        {
            object[] attributes = message.GetType().GetCustomAttributes(typeof(XmlRootAttribute), true);
            if (attributes.Length == 0) return message.GetType().Name;

            XmlRootAttribute xmlRootAttribute = attributes[0] as XmlRootAttribute;

            return xmlRootAttribute.ElementName;
        }
    }

This solution worked just fine, and the code ran correctly, but I still wasn’t happy with my solution. The problem I was sensing was that I was adding yet another extension method to Object, and Object’s neighborhood was already pretty crowded with all the Linq methods in there. I wanted my extension methods to show up only on those classes to which I wanted to apply them.

The solution that I came up with was to use a marker interface whose sole purpose is to limit the visibility of the extension methods to classes that I intend to apply them to. In this case, I made BaseRequest and BaseResponse each implement IMessageMarker, an interface with no methods. And I changed the extension method to be:

    internal static class SssMessageExtensionMethods
    {
        public static string GetCommandNameFromXmlRootAttribute(this ISssMessageMarker message)
        {
            object[] attributes = message.GetType().GetCustomAttributes(typeof(XmlRootAttribute), true);
            if (attributes.Length == 0) return message.GetType().Name;

            XmlRootAttribute xmlRootAttribute = attributes[0] as XmlRootAttribute;

            return xmlRootAttribute.ElementName;
        }
    }

Now I have the same extension method defined, but it only appears on those classes that implement the marker.

What do you think of this technique? In a more powerful language, like Ruby or C++ (ducking and running for cover!), this kind of trickery wouldn’t be needed. But C# can only get you so far, so I felt this was a good tradeoff between adding the methods for needed functionality and making the most minimal change in my classes to hide these methods so that only those places that needed them could see them.

— bab