Common Singleton Patterns

Another thing that we covered at my recent presentation was common use cases of Singletons.  The problem with artificial examples is that you’re often presented with objections that the point you’re making is restricted to the particular example you’ve given.  So, instead, let’s take a look at some of the most common usages of singleton patterns and explain why you’re breaking your code to use them:

The Current User

I’ve lost count of the number of times I’ve seen the current logged-in user accessed through a static method.  It’s extremely tempting: there’s a phenomenal number of parts of your system that rely on knowing it, and you don’t really want to keep passing the user around everywhere you go.

The problems start when you look at the implementation.  Chances are, if you’re writing a web application, you’re pulling that information out of the HttpContext (or worse, using a component that you don’t know uses the HttpContext).  The first time you try to add in some batch processing in a console application, you’re going to discover one of your main dependencies just fell away and you don’t have a backup.  You could try simulating HttpContext.Current, and you might even succeed (I doubt you’ll enjoy it) but you’ll now have a console app that pretends to be a web application just to support some code that you’re already starting to think of as legacy.

However, even if you could deal with this, you’ve got other problems.  What happens if you wanted to be able to impersonate another user?  It might not sound like much of a concern right now, but wait till you’re supporting the application and want to see what the other guy can see.  Sure, you could deal with this by hacking around with the static methods, but it would have been a whole lot easier if you’d just passed the correct routines what user you wanted.

Another concern: sometimes a workflow has to go through multiple users, an approval process is an obvious example.  Do you really want user A to ask user B to do something and then discover user B doesn’t have the permission?  Much better to be able to pass a user other than the current user into the permission logic and let user A be able to see who exactly can help him.  All of a sudden, your permission system doesn’t rely on the current user at all.

You might be thinking that all of this could be avoided by designing all of these features in at the start, but you’re going heavily into waterfall thinking there, a methodology that has been comprehensively found wanting.  Better is to start with a flexible design that allows you to change behaviour when you need to, and for that you need to be passing around instances, not calling static methods.

The Current Time

If you’ve got DateTime.Now in your code, there’s a good chance you’ve got a bug nearby.  Think about what happens when Daylight Savings Time kicks in.  However, even if you’ve changed your code to read DateTime.UtcNow, you’re still going to have all sorts of problems.  Here’s a concrete example: I have a order processing system with a batch job for Day End.  It uses the current time all over the place, including the truly basic task of working out what day it needs to be processing.

So, what if I want to run the batch on specific data?  On a day anything other than today?  Well, I’m going to have to change the system clock.  You thought it was bad trying to fake an HttpContext, faking the current time is much, much worse.  You’re actually messing with the BIOS.  All because you didn’t write the following code:

private interface IDateProvider {
    DateTime Now { get;  }

You can go significantly further down this road: I have unit tests in one project of mine that explicitly tests whether or not the code behaves correctly in Jersey City.  I wouldn’t be able to do that if I hadn’t abstracted out the concept of time from the system.


It’s amazing how many people approach logging through a singleton approach.  If you’re using a framework, you might not care about this:  there are people who’ve pretty much written the last word on logging and all you need to do is write a configuration file.  The very completeness of the solutions can lead you to thinking that static methods are the right solution for the problem.  Actually, they’re not.  The completeness of the solution has merely minimized the damage.

In our firm, we’ve got a set of static methods used to write to the event log.  Now, unlike using something like log4net, this isn’t a massively configurable and complete solution, it’s just what the developers at the time wrote.  So, you can’t affect policy: you can’t, for instance, filter out logging on any level other than changing the logging library.  You can’t disable logging if you’re running tests.  In practice, you can’t do very much at all.  Contrast this with the solution in one of our fix feeds.  It uses log4net, but more than that, it uses Castle’s logging facility.  Here, we get a logging object passed into the constructor of the class that needs logging.  This logger is specific to the class that is using it: try implementing that using static methods.  (You can: you just need to either pass the caller into every last call or walk the stack trace.  Neither solution is desirable.)

Again, the singleton pattern actually makes things worse, not better, for logging.


Anyone whose dealt with .NETs config files for a while will have come across some standard problems:

  • The typeless nature of AppSettings is a pain in the neck.
  • Access to configuration settings can come from anywhere.
  • You’ve often got to include multiple different settings for the same value, to support different assembly’s interpretation.

The second two are because ConfigurationManager is a singleton.

Let’s see how this happens: ConfigurationManager exposes a public static method for AppSettings.  Anyone can use AppSettings however they like. and guess what?  They do.  Now, here’s a common approach to dealing with this problem:

  • Only one class can access AppSettings.
  • Often, this class is a static class, so only has static accessors.
  • Any conversion to correct types is handled by this class.

Now, this is much better, and addresses the previous problems, but there’s still some problems.  The first comes directly from the singleton nature of the solution.  For instance, if you’ve got a single database connection, it might not seem like that big a problem, but the day you have two instances and want to load data from one to the other, you’ll discover that the fact your data access is hardwired to a particular configuration setting is causing you problems.  This is because you’re still breaking the Single Responsibility Principle: your data access class shouldn’t be making decisions about how to handle configuration, and accessing a static method on a configuration class isn’t different from reading the configuration setting directly as far as dependency management.

Another problem is that having a “configuration” class doesn’t really scale: the more assemblies you have, the less likely they are to want to share their configuration settings.  Now, you can always just simply have separate configuration settings for different concerns.  This is actually a good idea, but it still doesn’t deal with what happens when you actually wanted to share configuration settings.

Truth is, most classes and even most assemblies, shouldn’t need to know about configuration settings at all.  Configuration isn’t like logging: logging decisions have to be in the class doing the work, configuration decisions don’t.  Why not just pass the connection string into the constructor?  Same with the mail server, same with the retry policy.  Now, the only place that needs to read configuration is the Main method.

It’s all Microsoft’s Fault

Bill actually has a lot to answer for on this.  In each case we’ve deal with, the design of the .NET API has led us into long-term problems for a bit of short-term gain.  Developers often recognize that they’ve got a problem with HttpContext, the current time or configuration soup, but they don’t know what to do about it.  The .NET framework has lots of these somewhat curious decisions: an API is developed for the lowest common denominator, with the understanding that more sophisticated developers will code around it.  At least it’s usually possible to do so.  Static methods, where they have to be used, can usually be wrapped in instance methods with relatively few ill effects.  In the first case, a simple IIdentity interface which returns the name of the current logged on user can hide an awful lot of HttpContext-related problems.  But you do need to understand that this coupling happens, that it’s damaging and how you can avoid it.

To re-iterate, singleton patterns are dangerous, even those that Microsoft have implemented.

Microsoft’s Provider Pattern: A Bad Idea Carried Out to Perfection

Sun has always felt a need to educate its developers.  Sometimes this has led to Pearl Harbour scale disasters like J2EE, but it has also produced an extremely technically literate community.  On the other hand, sometimes you wish Microsoft didn’t even try.  I’ve pretty much come to the conclusion, for instance, that the Microsoft Enterprise Library is the Wrong Thing.  Every so often, we come across stuff which falls under the heading of “mistakes you need a PhD to make”, as Francis Fukuyama describes his advocacy of the invasion of Iraq.  The provider pattern is top of my list here.  If you’re not familiar with this, it’s a Microsoft-specific form of pluggable singleton.  It’s a singleton by virtue the “default provider” mechanism.  It’s extremely over-complex and, in my experience, just plain doesn’t deliver any benefits that plain old using constructors wouldn’t achieve better.

By combining the singleton pattern with a pluggable architecture, they hoped to draw the poison from the pattern.  Anyone who’s used it will know this isn’t the case. 

  • Sometimes the pluggability just plain fails: try find the parent node from a plugged sub-sitemap. 
  • Sometimes its insistence on using concrete types for everything makes your code nigh-on impossible to implement (especially if some third party made the same decision…)
  • Since it’s a singleton and hence can have shared state, you need to be writing thread-safe code.  Not a trivial task for a neophyte developer who just wanted a bit of pluggability.
  • Since it doesn’t have a coherent dependency injection model, you often end up using the Microsoft configuration model to get anything done.  (You do get a set of string name/value pairs, but any complex dependencies will fall down badly.)
  • Worst, when you finally discover that you actually wanted two of something, you get reminded that the provider pattern remains a special case of the singleton pattern.

It is in many ways really impressive, but that’s what makes it especially pernicious: it picks up a lot of developers who are trying to improve and leads them down blind alleys.  You can spend a lot of time supporting a provider pattern.  When you start to figure out that it’s not really paying back the investment, you’re going to feel that much of this patterns stuff is just nonsense.  Tell me you don’t know a developer like that…

Ironically, you know one really obvious user of the provider pattern?  Subtext, the blogging engine that powers, um, this site…

More about Singleton and Constructor Injection

So, I gave the first of my talks about Design Patterns last week.  I concentrated my attention on the Command and Singleton patterns.  My colleagues weren’t particularly interested in the Command pattern, but my remarks on the Singleton pattern raised a lot of interest.  For many, it was the first time they’d really heard someone come out and say that static methods were a bad idea.  It was ironic that Max Pool was blogging about the uselessness of evangelism on modern programming techniques while I was having a positive experience doing exactly that.

The thing is, everyone is used to a certain way of doing things.  They know that using static methods and shared state take time.  They know that they always end up with dependency soup, but it’s usually thought that this is just what programs are like.  To a certain extent, it’s always going to be hard to eliminate externalities, but it’s a lot easier than most people expect.

Constructor Injection, equally, is really easy to explain: you just pass things into the constructor.  Developers who write a lot of tests can instantly see the advantages of doing things that way.

None of this makes it easy to be the guy in the room saying the exact opposite of what most people expect, but it’s very rewarding when it comes off.

Here’s some talking points:

  • Business requirements change, they usually change in a way you’re not expecting.
  • If you only need one instance, creating it in the Main method and passing it into the objects that need it is much more flexible than using a Singleton pattern.
  • If something is public, it will get used, you can’t create a static method and then say that people shouldn’t use it.  They will, and it’ll be your fault.
  • Constructor Injection is a very low cost thing to implement when you’re writing new code. 
  • Refactoring old code to use it is much harder, but that reflects the refactoring challenges inherent in Singleton-style code.
  • If you’re passing a lot of objects down a function chain, that’s a code smell.  Chances are that the “group of objects” is a good candidate for a class.  Once you understand what that class is actually called, you’re on your way to a better design.
  • Passing lots of objects in constructor chains isn’t as easy to deal with.  Dependency injection containers make this problem manageable.  (Amongst other things…)
  • Evaluating all of your dependencies up front can lead to problems with circular dependencies.  Usually the best way to deal with this is to redesign objects so that they don’t have circular dependencies, but property injection can help in ugly cases.
  • Ironically, developers often spend a lot of time trying to think of the best way to make object interact, how to load configuration settings and so on.  Constructor Injection makes this simple: it’s always in the constructor.
  • Constructor Injection isn’t quite the end of the story.  If you actually need more than one object, we need to start talking about abstract factories.

The sooner you start using constructor injection, the sooner refactoring your code will stop feeling like playing Jenga.

Technorati Tags: Singleton,Inversion of Control,Abstract Factory

A Brilliant Diagnostic in Castle Windsor

I’m not massively fond of Castle’s diagnostics.  There’s certainly no general framework such as StructureMap has: you just ask for something and wait for the inevitable exceptions.  However, the guy who wrote this bit of code for PerWebRequestLifestyle will be bought a drink if I ever meet him:


It’s amazing how often people will write FAQs explaining obscure error messages when sticking the diagnostics directly into the code would be more convenient, both for them, and the users.

Technorati Tags: Diagnostics,Castle Windsor

Gang of Four Patterns: Table of Contents

Okay, so a blog isn’t the ideal format to dump 7000 words worth of thoughts on the subject of a book that weighs half a kilo.  🙂

I used to write film reviews: each fortnight I’d knock out about ten 50 to 100 word reviews of movies on in the local area.  I learnt a basic rule of criticism: it’s an awful lot easier to be nasty than nice.  I’ve had the same challenge here:  the better a pattern is, the harder I find to write about it.  Lord knows I find it easy enough to write about Singletons.

The dry and formal style of the Gamma et al disguises this problem: it attempts to be even handed the entire time, so the question of emphasis is moot.  Moreover, my opinion of what are the “best patterns” are, to a certain extent, coloured by my perception of which are “unobvious”.  Thus, those that I find hardest to describe are exactly those I want to describe the most.  (This isn’t strictly the case: I’d regard the visitor pattern as the hardest of the lot to describe.)

There’s also the difficulty that some of the patterns are so similar that they’ve generated an entire sub-industry discussing them.  I wouldn’t worry about this too much:  many patterns are useful only to the extent to which they clearly and succinctly describe a concept.

Table of Contents

Obviously, this being a blog, the structure of this changes with time.  Bits get revised and expanded upon.  This is a suggested reading order.  Patterns in brackets are not class Gang of Four patterns


Trash Talking?

A note about the last category: you could say I’ve trashed a third of the book, but that’s not the case.  What I’m saying is that modern practice has moved on:

  • Iterator and Interpreter are pretty much built in these days
  • Observer and Mediator are component of Publish/Subscribe
  • Bridge / Template Method / Strategy are special cases of good practice.
  • Flyweight, again, is basically just a special case of a more general piece of good practice.

So, they’re not terms I use (although Rx means I’ve got to dust off observable…) but that doesn’t mean the concepts are bad.  The only true anti-patterns are Singleton and Prototype.  (Memento isn’t that useful, but if you’re in its use case space and can’t achieve the same effect with an event driven design, it’s a good option.)

Beyond The Gang of Four

Here’s some patterns not listed that everyone should know:

  • Supervising Controller
  • Circuit Breaker
  • Publish / Subscribe (of course)
  • Dependency Injection, especially constructor injection. 
  • Unit of Work
  • Active Record

Maybe I’ll write some stuff about those another time.  For now, I have a presentation to give…

Technorati Tags:

*I’m going to have to do some work on observer.  My argument that you can ignore it and skip straight to publish/subscribe was fine as long as the Rx framework didn’t exist.

NOTE:  This article gets updated in line with the blog.

Complex Decision Making: Chain of Responsibility

This is the last pattern I’m writing up, and it’s one of my favourites.  The chain of responsibility pattern is a brilliant way of dealing with special cases and functional complexity, and it does it in a way that allows you to gain the advantages of hard coding without the disadvantages of inflexibility.  Here’s the basic idea: you have a list of Handlers.  Each has two operations:

  • Do I handle this message?
  • Process the message.

The original GoF statement of chain of responsibility implements the list as a linked list, hence the term “chain”.  This has the advantage of allowing handlers to act upon a message and pass it on, but this is rarely used.

Returning to the example I gave for the visitor pattern, we could implement handlers for executions, allocations and orders.  The chain would run through the list until it found a handler that dealt with the message, it would then dispatch the message to that handler.  The great strength of the pattern is dealing with special cases.  Let’s say that orders for one particular client always come with the price and the amount swapped round.  We can simply add an extremely special case handler that explicitly deals with this.

interface IRule<TValue, TResult> {
    bool Handles(TValue value);
    TResult Handle(TValue value);

The principal time that you know you want to use this pattern is when you see large amounts of special case code.  However, it’s also a good way of dealing with excessive generality:

  • Great big XML files
  • Database Decision Tables
  • DSLs

If you find yourself in a situation in which one of these is being proposed, it’s well worth examining whether or not a chain of responsibility would be better.  It can also be used in conjunction with these approaches.  For instance, one handler could be driven off a decision table, with a couple of special cases being handled by other handlers.  This can reduce the complexity of the decision table, so that it only deals with those cases which are easy to generalize.

I haven’t spent a lot of time on this pattern, because my personal experience was that I appreciated how useful it could be as soon as I saw it.

Enums are Evil: The State Pattern

This is actually about the state pattern. but let me talk first a bit about enums.  A big thing to think about is that “if” statements and especially “switch” statements can sometimes be a code smell.  Enums, in particular, can be a sign that something is wrong with your code.

Here’s an exercise to see exactly why enums are a problem: take some code you’ve written (not somebody else’s:  other people’s code is always bad…) and identify an enum that you’ve defined.  An enum with a large number of values is particularly promising, but even tri-states can illustrate the problem.  Now search through your code and document how often you branch on the basis of the enum.  I’m betting it’s pretty common.  Now, that in itself is a problem, but here’s where it gets worse: I guarantee that those branches are all over your code.  Picture what happens if you add in another entry to your enum.  Think of how many unrelated lines of code you’d need to check.  To make it harder, imagine that the new value is very similar, but not quite identical, in behaviour to another one.  It’s time, basically, to replace your enum concept with a proper class.

There’s three cases that you need to think about when looking at an enum this way:

  • Does the enum basically represent an action?  In that case, introducing a command pattern may be the best idea.
  • Is the enum mostly used to branch an algorithm?  Here, a strategy pattern-style outsourcing of responsibility may be the best approach.
  • Is the enum a changeable property of an entity?  In that case, the state pattern is probably appropriate.

I’ll observe that most of the arguments above also apply to boolean variables:  you need to be very careful with exposing state that is used for decision making in your code.  It can be very easy to end up with a mass of untracked dependencies.  In some ways, booleans can be even worse, because they’re harder to refactor out.

Java Enums

I’ve touched on the idea that a lot of patterns address deficiencies in our programming languages, and this is a classic case.  Enums in C# and C++ are basically a fairly light syntactic wrapper around an integer.  Enums in Java are much better.  They’re classes with a restricted number of possible values.  You can even overload methods for particular instances.  This makes implementing these patterns much more natural in Java than they are in C#.  I wish C# had Java’s enums, but it seems unlikely that Anders is going to bother.  So, to implement these patterns in C#, you’re going to need to do something like Kent’s approach for representing enums as classes.

On the other hand, it’s perfectly possible to introduce the same problems in Java code as in C# code if you don’t understand what the problem actually is.  In particular, liberally using the enum literals will drag you down the same road, no matter how good your intentions. 

The State Pattern

Quite often you have objects with a status or state pattern, usually representing a stage in a workflow process.  The state pattern doesn’t necessarily only apply to these cases, but it’s quite a common use case.  More generally, if a property of an object has significant behavioural implications, it can be a candidate for the state pattern.  To emphasize this, let’s take an example which isn’t a workflow state:

Let’s say we have a system for tracking changes to your live servers.  You’ve got three basic release types:

  • Routine maintenance
  • Ordinary, planned releases
  • Emergency work

Now, any given release might actually change which process it uses at any given time, complicating matters.  Consider if you want to know if a release is fully approved.  So, you represent the release type with a IReleaseType interface and add an IsFullyApproved method.  Here you’ve got a choice as to whether your release type object should take its parent object as state.  If it does, the interface is simpler since it doesn’t keep having to ask for the parent object.  On the other hand, it’s no longer got useful enum behaviours such as there only being one instance representing “Routine Maintenance”.  You’re not violating best practice either way.

You should definitely take a look at Davy Brion’s implementation of the circuit breaker pattern, which uses a state pattern.  (Incidentally, if you’re having trouble following the code, bear in mind that a circuit breaker prevents activity when it’s open.  When it’s closed, it passes electricity through.)

Enums as Classes

Although the State pattern is a useful and important pattern, it’s part of a much larger approach: getting rid of enums and replacing them with classes.  We’ve seen that Command and Strategy can also be used to address similar concerns.  Don’t get too hung up on whether it’s a State, Strategy or Command: replacing a rather fragile enum with a proper object instance is the order of business.  Once you’ve made the decision, a lot of standard object design principles will come into play, making the design more obvious.  As a rule of thumb, try to avoid referring to an exact enum:  e.g. “State.Open” unless you’re actually passing something to a constructor or writing a test.  The rest of the time, it should be the methods and properties of the “state” that are being used.

Some more things you need to deal with when using this pattern: what you do about persistence.  Basically, is your enum-like object an entity or just a value?  Both have their advantages.  if you want to go with a value, you’ll need to deal with persistence concerns: implementing IUserType for NHibernate and implementing a model binder in ASP.NET MVC.

Going Cold Turkey on Static Methods

I recently had a rather incoherent rant about why Singleton is an anti-pattern.  Let’s say that you decided that static methods needed to be eliminated from your code base.  So you embark on the refactoring to end all refactorings.  That’s exactly the situation I’m in at the moment.  The irony is that the static methods I’m trying to eliminate are calls to StructureMap’s ObjectFactory.GetInstance.  Yes, riddled through the code are calls to services.  Nothing is denied to any object. 

If you start trying to replace static methods with proper instances, you’re going to be asking yourself a lot:

  • Why does that object need a connection to that system?
  • For crying out loud, why do I need to add an extra constructor parameter to support only one method?
  • Why exactly can’t I just store the current user somewhere?
  • But now I’ve got X, which has a dependency on Y, and Y has a dependency on X, does this make any sense at all?
  • How many methods am I going to have change?
  • Does everything have to be an instance method?
  • Exactly how many levels do I need to pass this object down?
  • Why does this object take a dependency on every service?
  • How long is this going to take?
  • Is this really worth it?

The answer to the last question is yes

Static methods are like crack, they’re convenient, they solve your problems quickly and you quickly become dependent upon them.  You’re so dependent you don’t even know you’ve got a problem.  You may even read an article like this and believe that it doesn’t apply to you, because you’ve got your static methods “under control”.

Now, if you’ve never done experienced a code base that’s not riddled with static methods, you’ve never felt what it is to be clean, to be able to analyze your dependencies as easily as being able to examine your constructor, to be able to replace sections of your system and build new systems out of the components you’ve created without worrying about support functionality you’re not actually using.  It feels good, but before that, it’s going to feel really bad.  I don’t mean really bad in the “non-technical manager who always opposes refactoring” bad, I mean bad as in “This was a huge mistake and I’ve no idea how I’m going to get it working again” bad.

What’s worse, going cold turkey is something you have to do on your own.  Solving this one is hard even for other team members to help you.  Branching is going to help you this time; it’s best to just have a code freeze.  But I figure it won’t hurt to talk, so here’s answers to the questions earlier:

  • Almost certainly, because your object design is wrong.  Just get it working.  We’ll worry about how to fix the design another time.
  • Well, you might not have to.  I’ll show you how to deal with that later.
  • You can, but that “somewhere” is going to be another constructor parameter e.g. ICurrentUserProvider. 
  • It doesn’t, and it never did.  It’s just that static methods allowed you to continue with this state of affairs.  You’re going to have to break the circular dependency.
  • About 50%.  I didn’t say it was going to be easy.
  • Yes, it pretty much does.  It doesn’t really perform any worse, so don’t worry about it.
  • Ridiculous numbers, especially if your object design is wrong or you’re not using a dependency injection tool.  Just live with it for now, we’ll come back to this another time.
  • It took me three hard slog days with pretty much the entire code base checked out.
  • Because it’s assaulting the single responsibility principle with an axe.  You’re going to want to restructure this at some point.  Not now.

Reversibility Patterns: Memento and Command

These two patterns deal with times that you’ve got a requirement to be able to undo work.  There’s Memento, which is a pattern of limited use (if only because a lot of the classic implementations are already available for you to use), and Command, which is one of the most criminally under-used patterns in the whole book.


Let’s deal with Memento first.  Personally, I think most of the problem with Memento is its name.  It’s a checkpoint.  You store checkpoints as you’re working, and you restore back to a checkpoint if something doesn’t work.  A good design for a limited set of use cases.  Why aren’t you going to need this very often:

  • Because you’re using a transactional system such as a database and can use the transactions directly.
  • Because you’ve followed good design principles and avoided having a lot of mutable state in your code.
  • Because your reversibility concerns are handled by using the command pattern.

If you’re wondering how on earth you could implement this behaviour without mutable state, try taking a look at Eric Lippert’s post on immutable stacks.  Usually, an approach like this is likely to be a better solution.

An interesting example where it is (probably) used is Prince of Persia: Sands of Time.  In the game, you can hit a button that reverses time.  By storing the state of every actor in recent frames, it can just as easily rewind them.  The example also highlights the importance of keeping the mementos small: if it, for instance, chose to serialize the walls every frame, the game would grind to a halt. 


Let’s be clear: the command pattern is stone cold brilliant.  I know I’ve just been going on about the Memento pattern.  Now it’s time to wake up.  Also every UI you create, every workflow you implement, has a Command pattern in it.  Well actually, it doesn’t, because you don’t know the Command pattern and it’s not obvious.  But it should.

Here’s the basic form of the command pattern:

interface ICommand {
    void PerformAction();

Now, in itself, this isn’t that interesting.  So far, we’ve managed to represent an action (code) as an object (data).  As such, it might as well just be a function delegate.  However, where things get interesting is in the principal variation to the pattern.

Undo Command

To add reversibilty, we can extend the interface like this:

interface ICommand {
    void PerformAction();
    ICommand UndoCommand();

We’ve got something much more interesting.  All of a sudden we’ve got a pattern that you should be implementing in every GUI you ever write.  This is the answer to how Word allows you to undo multiple operations.  If we return to the Prince of Persia example, each monster would have a currently executing command, and the command object would need to provide additional information should as animation frames.  (Don’t worry, I’m not about to start blogging about how to write a computer game.)

The reason this is so hugely important is that you need it from Day One.  Adding undo features to a design that doesn’t implement the command pattern can be an exercise in frustration.  Obviously, the undo command of an undo command should be a redo command.  Generalizing further, you get to concepts such as the layers in PhotoShop, where you keep track of your action history on an object and can insert and replace actions. 

You’ll note that GMail generalizes this concept in a couple of interesting ways:

  • A “following command” concept.  This is usually undo, but can be something else.  For instance “send an email” has a following command of “view the email you just sent”.
  • Actually, sometimes there are multiple following commands.  This enables such functionality as “Invite this user to gmail”.
  • Certain commands cannot be undone, and the UI supports highlighting those exceptions.  (You could just implement this by returning null for the Undo command, but that would prevent you from specifying behaviours when reversibility is lost.)

Serializing Commands

It’s often an excellent idea to make your command objects serializable, both in the sense of supporting .NET serialization and also in the more general sense of being able to round-trip the object to the database.  You can do the following

  • Provide a complete audit log of your user’s actions
  • More, be able to replay a user’s session.
  • Analyze usage patterns to spot common behaviours.
  • Distribute your application across multiple servers, probably by using a publish/subscribe network such as nServiceBus.

Using Commands to make Transactions

Obviously, one obvious model for implementing rollback is the Memento pattern.  However, it’s also possible to use the Command pattern for this purpose.  The following code illustrates how:

void PerformTransaction(IEnumerable<ICommand> commands)
    Stack<ICommand> executedCommands = new Stack<ICommand>();
    foreach (var command in commands)
        } catch
            foreach (var commandToRollback in executedCommands)


We’ve covered the two main patterns to implement reversibility.  In practice, the Memento pattern is often quite brittle.  Changes in the behaviour of related objects could lead to changes in what has to be stored.  This is less likely to happen with the Command pattern, since it separates out the responsibility for reversibility into the relevant transitions.  Furthermore, command objects can be extended in further directions, taking in permissions, interruptibility, batching, to name but a few.

So, why isn’t it more heavily used?  Why is it that I always see UIs that desperately try to solve the problems the Command pattern solve in ad hoc and incomplete ways?  I think the problem is that it’s quite hard to refactor to use this pattern:  there’s just too many parts of your code affected by pulling the command concerns together.  This makes it all the more important that you design in Commands right from the start of your project.

Double Dispatch: The Visitor Pattern

I’ll be frank, I don’t like the Visitor Pattern.  It’s a hack.  It’s just a way of getting around a deficiency in the language.  Basically, extending the functionality of objects is what inheritance is for.  The whole reason the visitor pattern exists is to deal with the times that this model falls down.  Proxies and the decorator pattern could also be considered object extension mechanisms, but I’ve already dealt with them.  Another reason I don’t like it is that it relies fairly heavily on abusing function overloading, and it’s extremely brittle with regards to changes in your inheritance structure.

A note: it is often assumed that the visitor pattern has something to do with iteration and trees.  Whilst it can be used in such scenarios, it’s not really the point and often there’s a simpler solution.  So, what I’m going to talk about is double dispatch.

There’s basically two limitations to virtual methods:

  • You can’t add them to an existing class.
  • Sometimes you don’t want to add them to an existing class.  This is usually because doing so would violate the single responsibility principle.

The visitor pattern is a way around this limitation, but it’s not elegant.  What’s worse, it requires you to be able to modify the target classes, so it doesn’t even fully address the first limitation. Whilst it can be useful, it’s always worth examining exactly why you need a visitor.  It can be a code smell.

Implementing the Visitor Pattern

Let’s say that we wish to write a routine that processes messages in a trading system.  We’ll say for the sake of argument there are order messages, execution messages and allocation messages.  Now, the “object orientated” way of doing this would be to add processing method directly to the class, but that isn’t possible or desirable in C#.

So, we define a “visitor” interface

interface IMessageVisitor {
    void Visit(OrderMessage message);
    void Visit(AllocationMessage message);
    void Visit(ExecutionMessage message);

and we add a method to the IMessage interface.

void Visit(IMessageVisitor visitor); 

It’s probably worth defining an interface IVisitable<TVisitor> for this purpose. 

internal interfaceIVisitable<TVisitor> {
void Visit(TVisitor visitor);

We now implement the following method in every one of our target classes:

void override Visit(IMessageVisitor visitor) { visitor.Visit(this); }

Note that you can’t implement this code the once in a base class, because it won’t work.  What this code does is to abuse function overloading.  If the message is an allocation message, it will call the “Visit Allocation Message” routine.  If you’ve got an “Automated Allocation Message” that inherits from allocation message, it’ll call the same routine.  The same semantics, in other words, as a virtual function.

If, on the other hand, you wanted to specialize the “Automated Allocation Message”, you’d need to change the IMessageVisitor.  It’s not a perfect solution.

Alternatives to the Visitor Pattern

It’s worth noting that many modern “typeless” programming languages allow you to add methods directly to classes at runtime.  This provides a strong alternative to the visitor pattern.  It doesn’t violate the single responsibility principle as long as you segregate the scope of the routines.  If you can’t modify the target classes, a (carefully written) big ugly cascading if statement can be used instead of implementing IVisitable.  Finally, you could use a chain of responsibility instead, which is effectively a well-structured cascading if statement, but a lot more flexible. 

The catch is: any of the above solutions don’t get you the magic static type checking of the visitor pattern.

In general terms, if you’ve only got a small number of implementations of a given IVisitor class, you should probably just consider adding virtual functions directly to the calling classes.  If, on the other hand, you have fifty, the visitor pattern may be pretty much the only way to keep your problem space manageable.

Tree Walking

The classic gang of four example of tree walking is actually a mix of the visitor pattern and the composite pattern.  With this, the parent nodes visit method automatically call visit on their children.  Seriously, just don’t do this unless you absolutely have to.  You’ve mixed the dispatch behaviour with iteration behaviour, there’s no way for the caller to figure out the structure of the tree and you can’t vary between depth and breadth first iteration.  Here’s some code that’s often more useful than doing the composite and visitor trick:

interface INode<TNode> {
    IEnumerable<TNode> Children { get; }
IEnumerable<TNode> DepthFirst<TNode>(TNode root) 
where TNode: INode<TNode>
    return new[] { root }.Union(root.Children.SelectMany(c => DepthFirst(c)));
IEnumerable<TNode> BreadthFirst<TNode>(TNode root)
where TNode : INode<TNode>
    return BreadthFirst<TNode>(new[] { root });
IEnumerable<TNode> BreadthFirst<TNode>(IEnumerable<TNode> children)
where TNode : INode<TNode>
    return children.Union(children.SelectMany(c => BreadthFirst(c)));
Technorati Tags: ,

UPDATE:  This article used to contain text about the composite pattern, which I’ve removed.  You can find my revised thoughts about composite pattern here, or the original text with editorial here.