1

I have found 2 questions here asking the difference between Camel's .end() and .endChoice(). And this is not an issue for me. It is quite clear for me that .end() is used to finish .choice() blocks and .endChoice() is used to finish .when() blocks.

However, my issue is... what's the point about using .endChoice()s, after all? Is it just about getting the code more legible?

Look at these examples (please, do not point out about correctness or usability of this, my point here is understanding the mechanism, not asking for clean code models):

CODE SAMPLE 1:

from("file:files/input")
            .choice()
                .when(simple("${file:ext} ends with 'xml'"))
                    .log("LOG 1")
                    .choice()
                        .when(simple("${file:ext} ends with 'xml'"))
                            .log("LOG 1 nested")
                        .endChoice()
                        .when(simple("${file:ext} ends with 'xml'"))
                            .log("LOG 2 nested")
                        .endChoice()
                .endChoice()
                .when(simple("${file:ext} ends with 'xml'"))
                    .log("LOG 2")
                .endChoice()
                .otherwise()
                    .log("NOT AN XML FILE")
            .end().to("file:files/output");

CODE SAMPLE 2:

from("file:files/input")
            .choice()
                .when(simple("${file:ext} ends with 'xml'"))
                    .log("LOG 1")
                    .choice()
                        .when(simple("${file:ext} ends with 'xml'"))
                            .log("LOG 1 nested")
                        .when(simple("${file:ext} ends with 'xml'"))
                            .log("LOG 2 nested")
                .when(simple("${file:ext} ends with 'xml'"))
                    .log("LOG 2")
                .otherwise()
                    .log("NOT AN XML FILE")
            .end().to("file:files/output");

I tested putting xml files in the files folder, and both codes do EXACTLY the same thing. Whether you use .endChoice()s or not, .when()s ALWAYS behave as "elseif" statements, that is, the response is "LOG 1" and "LOG1 nested", and the "LOG2" and "LOG 2 nested" never print. If the file is not xml, the otherwise route is triggered as expected.

Hope what I'm asking is clear. Best regards.

LeoAlmDiniz
  • 75
  • 12

1 Answers1

4

.endChoice is simply a workaround to compensate limitations regarding the Camel DSL.

Your examples work fine because your when block have a very simple content. If you put more complex EIPs into them, you can get into situations where your code does not compile without .endChoice.

Look at this example on the Camel website with such a case.

I also had rare situations where even .endChoice didn't help. But normally in such cases the route is too complex anyway and should be split.

burki
  • 6,741
  • 1
  • 15
  • 31