Ayende @ Rahien

Refunds available at head office

Design patterns in the test of time: Chain of responsibility

The chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects. Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain. A mechanism also exists for adding new processing objects to the end of this chain.

More about this pattern.

It is actually quite common to see this pattern now-a-days using events. Something like CancelEventArgs and a CancelEventHandler to handle the FormClosing event of a Form.

We use Chain of Responsibility in RavenDB in several places, like this one:

foreach (var requestResponderLazy in currentDatabase.Value.RequestResponders)
{
  var requestResponder = requestResponderLazy.Value;
  if (requestResponder.WillRespond(ctx))
  {
    var sp = Stopwatch.StartNew();
    requestResponder.Respond(ctx);
    sp.Stop();
    ctx.Response.AddHeader("Temp-Request-Time", sp.ElapsedMilliseconds.ToString("#,# ms", CultureInfo.InvariantCulture));
    return requestResponder.IsUserInterfaceRequest;
  }
}

Note that we have moved on the the behavioral patterns, and those tend to have withstand the test of time much better, in general.

Other places where Chain of Responsibility is used is request routing and error handling. A common approach is to also have this done by delegating, where I am handling what I can and passing on to the next object if I don’t know how to handle a request.

Recommendation: This is still a very useful pattern. One thing to note is that it is effectively an O(N) operation with respect to the number of items in the chain that you have. As usual, do not overuse, but it is a really nice pattern.

Comments

tobi
11/16/2012 02:44 PM by
tobi

And you might want to merge WillRespond and Respond into one call so that the responder class has an opportunity to avoid redundant computations.

Rangoric
11/16/2012 04:01 PM by
Rangoric

I like the separate methods on the class/interface for Will Response and Respond. It avoids having a check condition at the start of respond, and also makes sure that the names on the methods encompass all that the method will do.

It also makes the unit tests nicer.

Mystical
11/16/2012 05:47 PM by
Mystical

Does that code fully qualify as chain of responsibility? I thought the pattern was for the first object to decide whether it can act and then forward the call to the next object?

Karep
11/16/2012 08:51 PM by
Karep

Same question as Mystical. Not sure if this is Chain of responsibility

Mystical
11/17/2012 12:33 AM by
Mystical

Rangoric - It's a good practice to have the bool check in addition to the method, but if you were implementing this, Respond should still call WillRespond and throw an exception if it can't (just like File.Exists and File.Read)

Ayende Rahien
11/17/2012 05:41 PM by
Ayende Rahien

Mystical, Why on earth do I need to call WillRespond twice? It is already checked by the calling code. Doing double checks like that is pretty useless, you need to trust your callers, especially when they are the infrastructure.

Mystical
11/18/2012 11:25 AM by
Mystical

Ayende - I'm thinking of a public API here where if you have a method that can throw an exception if a certain condition is not met, then having a method which will test that the condition is met before calling the other method is a good idea (as in the File.Exists, File.Read example). You are giving the caller the ability to avoid an exception which is a good thing!

If it's all internal code and you can guarantee the behaviour of the caller then maybe it's unnecessary but I would think that relying on the caller to behave in a specific way without enforcing it is a dangerous assumption even for internal code if you have multiple people using it who may not be familiar with the intricacies of the API!

Mystical
11/18/2012 11:34 AM by
Mystical

Ayende - Just noticed your reply "Mystical, Does it matter if you call each other or it is a loop? It is the same basic principal." seems you posted it on the ASP.NET Caching post instead of this one.

My point was that there is no "chain" here, none of the RequestResponder instances know about their successor (the responder that they would call if they can't handle the input themselves).

Hendry Luk
11/19/2012 03:54 PM by
Hendry Luk

I'm with Mystical. A good example of chain-of-responsibility pattern is interceptors in Castle. Each interceptor has a reference to an IInvocation (which encapsulates the next interceptor in the line), thus allowing each interceptor to pass part of its responsibility to the next node in the chain, or even to terminate the chain altogether. The given example on this post does not allow that.

Lokesh
11/27/2012 11:14 AM by
Lokesh

I have used this pattern in one of my project.. and I must say that it is savior where ever it fits good. By the way, I used it when calculation various SLAs for a task.

Andrew
11/30/2012 02:13 PM by
Andrew

I love this pattern and I use it somewhat frequently. Like any tool that gets used often enough, the chance arises that you can misuse it. As a cautionary tale to those who come after, here's where I most recently went wrong. I used this in place of something that would be better serviced as a state machine. It ended up being really complex with either requiring too many links in the chain, or "CanHandle" checks being way too long. I'm sure there's other ways to misuse this pattern (just like every pattern) but there was mine.

Comments have been closed on this topic.