Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the advantages of chain-of-responsibility vs. lists of classes?

Recently, I was discussing with another programmer the best way to refactor a huge(1000 lines) method full of "if" statements.

The code is written in Java, but I guess this issue could happen in other languages such as C# as well.

To solve this problem, he suggested using a chain-of-responsibility pattern. He proposed having a base "Handler" class. Then, "Handler1", "Handler2", etc. would extend "Handler".
Then, handlers would have a "getSuccessor" method, which would either return null(if it was the last of the chain) or the next Handler of the chain.
Then, a "handleRequest(Request)" function would either deal with Request, or pass it to the next of the chain and, if none of the previous solutions worked, it would return just null or throw an exception.
To add a new Handler to the chain, the coder would go to the last element of the chain and tell it there was a new element. To do something, he'd just call handleRequest on the first element of the chain.

To solve this problem, I suggested using a different approach.
I'd have a base "Handler" class as well, with "Handler1", "Handler2", just like the previous method mentioned.
However, there would be no "getSuccessor" method. Instead, I'd have a Collection class with a list of handlers(a Vector, an ArrayList, or whatever is best in this case).
The handleRequest function would still exist, but it wouldn't propagate the call to the next handlers. It would just process the request or return null.
To handle a request, one would use

for(Handler handle : handlers){
    result = handle.handleRequest(request);
    if(result!=null) return result;
}
throw new CouldNotParseRequestException(); //just like in the other approach

Or, to prevent code duplication, a "parseRequest(request)" method could be added to the collection class. To add a new handler, one would go to the collection constructor(or static{} block, or something equivaleng) and simply add the code "addHandler(new Handler3());".

Exactly what advantages of chain-of-responsibility am I missing with this approach? Which method is best(assuming there is a best method)? Why? What potential bugs and issues can each design method cause?

For those who need context, here is what the original code looked like:

if(x instanceof Type1)
{
//doSomething1
} else if(x instanceof Type2)
{
//doSomething2
}
//etc.
like image 538
luiscubal Avatar asked Jun 28 '09 17:06

luiscubal


People also ask

What is the difference between chain of responsibility and decorator patterns?

The chain-of-responsibility pattern is structurally nearly identical to the decorator pattern, the difference being that for the decorator, all classes handle the request, while for the chain of responsibility, exactly one of the classes in the chain handles the request.

Why would I ever use a chain of responsibility over a decorator?

Decorators can be thought of as executing all at once without any interaction with the other decorators. Links in a chain can be thought of as executing one at a time, because they each depend on the previous link.

What is the characteristics about chain of responsibility in what scenarios can chain of responsibility be used?

As the name suggests, the chain of responsibility pattern creates a chain of receiver objects for a request. This pattern decouples sender and receiver of a request based on type of request. This pattern comes under behavioral patterns. In this pattern, normally each receiver contains reference to another receiver.


2 Answers

Which approach is best depends on what your handlers want to do.

If the handlers can completely handle a request request on their own, your approach is fine. The handlers do not have a reference to other handlers, which makes the handler interface simple. Unlike the standard implementation of Chain of Responsibility, you can add or remove handlers from the middle of the chain. In fact, you can choose to build different chains depending on the type of request.

One problem with your approach is that a handler cannot do pre-processing or post-processing on the request. If this functionality is required, then Chain of Responsibility is better. In CoR, the handler is the one responsible for delegating to the next handler on the chain, so the handler can do pre-processing and/or post-processing, including modifying or replacing the response from the next handler on the chain. In this way, CoR is very similar to Decorator; it's just the intent that's different.

Since in CoR, the handler keeps a reference to the next item on the chain, you cannot add or remove items from the middle of the chain. A variation of CoR that allows you to add or remove items from the middle of the chain is a Filter Chain (see, for example, javax.servlet.FilterChain).

The code example you showed was a bunch of "if" statements that did different behavior based on the type of an object. If that is typical for the code you are cleaning up, you can simply have a map from the request type to the handler required.

Another approach to removing "if" statements is inheritance. If you had some behavior that you needed to do, and there was one variation for a web server, and other variation for a SOAP server, you could have a WebServerRequestHandler and a SoapServerRequestHandler, each extending RequestHandler. The advantage with inheritance is there a clearer place to put logic that is common to both types of request. The disadvantage is that since Java doesn't have multiple inheritance, you can only model single-dimensional problems.

like image 187
NamshubWriter Avatar answered Oct 11 '22 14:10

NamshubWriter


I like your idea with collection better than those successors. It makes it easy and clear to manipulate this set of handlers: the collections interface is well known and everybody understands how to iterate over a List or what not.

If you use this successor way suggested by a friend, take care not to fall into a very deep recursion (unless your platform supports tail calls, I don't know if JVMs are capable of that).

I wouldn't recommend adding any methods to the collection. You get much more complicated design that's harder to comprehend and harder to modify. There are two separate concerns: storing a set of handlers and the interpretation of this handlers as a chain of responsibility. A method that handles requests by iterating over a collection is on higher level of abstraction than collection housekeeping methods, therefore shouldn't belong to collection interface.

like image 41
Tadeusz A. Kadłubowski Avatar answered Oct 11 '22 14:10

Tadeusz A. Kadłubowski