Ayende @ Rahien

Hi!
My name is Ayende Rahien
Founder of Hibernating Rhinos LTD and RavenDB.
You can reach me by phone or email:

ayende@ayende.com

+972 52-548-6969

@

Posts: 5,947 | Comments: 44,540

filter by tags archive

Design patterns in the test of timeChain 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.

More posts in "Design patterns in the test of time" series:

  1. (21 Jan 2013) Mediator
  2. (18 Jan 2013) Iterator
  3. (17 Jan 2013) Interpreter
  4. (21 Nov 2012) Command, Redux
  5. (19 Nov 2012) Command
  6. (16 Nov 2012) Chain of responsibility
  7. (15 Nov 2012) Proxy
  8. (14 Nov 2012) Flyweight
  9. (09 Nov 2012) Façade
  10. (07 Nov 2012) Decorator
  11. (05 Nov 2012) Composite
  12. (02 Nov 2012) Bridge
  13. (01 Nov 2012) Adapter
  14. (31 Oct 2012) Singleton
  15. (29 Oct 2012) Prototype
  16. (26 Oct 2012) Factory Method
  17. (25 Oct 2012) Builder
  18. (24 Oct 2012) A modern alternative to Abstract Factory–filtered dependencies
  19. (23 Oct 2012) Abstract Factory

Comments

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

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

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

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

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

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

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

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

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

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

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.

Comment preview

Comments have been closed on this topic.

FUTURE POSTS

No future posts left, oh my!

RECENT SERIES

  1. RavenDB Sharding (2):
    21 May 2015 - Adding a new shard to an existing cluster, the easy way
  2. The RavenDB Comic Strip (2):
    20 May 2015 - Part II – a team in trouble!
  3. Challenge (45):
    28 Apr 2015 - What is the meaning of this change?
  4. Interview question (2):
    30 Mar 2015 - fix the index
  5. Excerpts from the RavenDB Performance team report (20):
    20 Feb 2015 - Optimizing Compare – The circle of life (a post-mortem)
View all series

RECENT COMMENTS

Syndication

Main feed Feed Stats
Comments feed   Comments Feed Stats