Page 1 of 1

benefits CoR over looping over the handlers?

Posted: Sat Mar 21, 2009 12:49 pm
by koen.h
What are the benefits of the Chain of Responsibility over having an array with those handlers and looping over them until one handles the request? E.i. is there a situation where the CoR would be better suited than the other?

Re: benefits CoR over looping over the handlers?

Posted: Sat Mar 21, 2009 10:10 pm
by Christopher
I am not sure that there is a design difference between the two. It sounds like an implementation difference. As I recall there is some disagreement as to whether the chain can end itself or runs to the end. But you can pass (Command) objects through Filters/Handlers how ever you thing works best.

Re: benefits CoR over looping over the handlers?

Posted: Sun Mar 22, 2009 12:54 am
by Chris Corbyn
I know the former will use plenty of memory for larger chains due to the ever increasing size of the call stack. But as arborint says, Chain of Responsibility is able to break the chain itself with a clean algorithm.

J2EE uses CoR for Request filtering before the Request ever reaches the ServletContext. This can be useful if you want to intercept the request and return early preventing the end of the chain from being reached.

Another example of where CoR may be a better choice is an event queue where several listeners will receive the event (events seem to be the typical use case for CoR), but one of those listeners decides to terminate the event bubble, this terminating the chain early.

Re: benefits CoR over looping over the handlers?

Posted: Sun Mar 22, 2009 5:08 am
by koen.h
I consider being able to break the chain one of the drawbacks of the CoR.

Re: benefits CoR over looping over the handlers?

Posted: Sun Mar 22, 2009 5:29 am
by Chris Corbyn
koen.h wrote:I consider being able to break the chain one of the drawbacks of the CoR.
It depends on whether or not this is a requirement, or a side-effect. For some chains it's a requirement, like I mentioned, J2EE's FilterChain for the Request. J2EE wants you to be able to say "hey, we're done with this request, dump the response now and forget passing it all the way to the ServletContext".

Another benefit is the ability to filter multiple (related) objects in the same chain and to swap out what is being filtered transparently.

http://java.sun.com/j2ee/tutorial/1_3-f ... lets8.html

But yes, most filter chains are intended to process the input through each and every filter, so you may consider it a "risk" to be able to end the chain.

Just use the implementation that fits your needs best. I'm sure you'll find a use for CoR at some point...