4

I have legacy code and it has a function called initialize and this function calls N amount of methods of same object and these methods are responsible for validating identity of personas.

At each method call, the function checks whether the said method approved or disapproved the persona. If the method returned 0 then it assume the method disapproved the said persona and return an error.

I want to refactor this into an elegant way. I found Chain of Responsibility pattern, but it seems from the examples I found that this pattern is for multiple instances of an object rather a single instance.

Can I use this pattern for single instance as-well?

1 Answer 1

3

Design patterns are not a catalogue of ideas in which you chose solutions to your problems. Try to solve your problem and only if you encounter a known problem should you consider the pattern. This is why the intent matters. For the chain of responsibility, it's:

Avoid coupling the sender of a request to its receiver, giving more than one object to handle the request.

Does this match your real problem? I understand that your intialize() function calls for a single object its method1() to methodN() and if only one of this method returns an error code (because of missing authorizations / unaccepted persona), initalize() returns an error. To succeed, all the invoked methods must return a non zero result.

It appears that your intent is completely different: it's not about decoupling the sender from the reveiver. It's about the same receiver successively handling different requests. And more precisely, it's about calling a predefined set of methods in a given order. The chain pattern would be an overkill here:

  • You'd need to create the chain by registering each successive method to call as a Handler object;
  • Since the chain pattern is based on an abstract Handler class with a single method to handle the request, you'd need to create N adapters, one for each method, that each hold a reference to your single instance, and a link to the successor.
  • Not only would this require a lot of boilerplate code for the adapters, but your adapters would need to hard-wire to specific methods; so instead of decoupling, you'd on contrary tightly couple.

There are much simpler solutions: You could just consider a simple logical chaining. Depending on the language you could for example write:

bool success = o.method1() && o.method2() && ... && o.methodN();  

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.