0

Why I need to use CoR if I could write if-else and instead of passing through multiple handlers I could just find whatever handler I need and delegate the processing to the specific one.

I think, CoR is not being used as a pipeline to process the same request in multiple handlers (like this: https://github.com/RichJones22/chainOfResponsibility_cpp/blob/master/main.cpp). So why I use CoR at all?

Narek
  • 35,407
  • 69
  • 202
  • 359

2 Answers2

1

What are the advantages of CoR?

You are correct that it is a kind of pipeline; each step of the pipeline interacts with the next step through the base class interface. You can use it if each of the pipeline steps do not depend on/are tied in with the context of the previous steps directly.

Each class would implement its own stage of the pipeline, advantages are:

  • modularization: each pipeline class treats its well defined aspect/command; the code of each command object/pipeline stage is supposed to be cleaner and easier to read/maintain.

  • one advantage is that you can debug/test each of these classes separately, independent from the rest of the command/pipeline classes; this is great if you have unit tests.

  • you can configure different instances of pipelines in a factory/builder class and treat the command classes as building blocks and stack them up depending on configuration/actual requirements.

    one example is a logging stage; you would add a derived class that just does logging and add it to the end of the pipeline, i an event must be logged; if you are in a 'no logging mode configuration' then you will not stack up this command object.

MichaelMoser
  • 2,662
  • 1
  • 20
  • 24
0

If you'll have to execute 4 out of 10 elements in chain in one case, and 2 in other case and 9 in another case then CoR is clearly better than ton of nested if statements.

Consider classical implementaion such as chain of validators. You can plug in and out some of validators in specific cases, you can fail on first validation error, or just collect all of them.

Marcin Szymczak
  • 9,665
  • 4
  • 48
  • 60
  • What is classic CoR only one handler processes and exits or several can process and it is still CoR? – Narek Sep 02 '15 at 13:09
  • I have never seen different name for the other kind. It seems that every behavior which sounds like: "pass data through chain of methods" is called CoR. – Marcin Szymczak Sep 02 '15 at 13:13