Many Builder Templates

I read Joshua Bloch's Effective Java, where in paragraph 2 he mentions the benefits of using the Builder pattern when working with multiple parameters in the constructor. Everything is fine until I saw the difference in var-args between the regular constructor and this template. So, I have some doubts about this:

  • How does the builder pattern allow multiple var-args?
  • Why does a regular constructor allow only one var-arg? (Perhaps due to the fact that this will cause ambiguity in case there are several var-args, when a certain data type is the same for both, but I'm not sure if this is the right reason.)

I have not used var-args in my code, but yes, I know their use. However, I cannot understand the reason for the above statements. Any help would be appreciated.

+4
source share
1 answer

No method signature (included constructors) allows multiple varargs. There can only be one, and it should be the last argument.

This is just a limitation in the language specification. And yes, the reason for this is that it can become very ambiguous very quickly if you allow more flexibility.

There is no such restriction in the builder pattern, since each parameter can get its own method.

  builder
    .withOptions("a", "b", "c")   // varargs
    .withColors("red", "blue")    // more varargs
    .build();
+6
source

Source: https://habr.com/ru/post/1616686/


All Articles