Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Builder pattern multiple varargs [duplicate]

I'm reading up Joshua Bloch's 'Effective Java' where in Item 2, he mentions the advantages of using Builder pattern when dealing with several parameters in the constructor. All's good, until I saw the multiple var-args difference between the conventional constructor and this pattern. So, I have some doubts regarding it :

  1. How does builder pattern allows for multiple var-args?
  2. Why does a conventional constructor allows for only a single var-arg? (Maybe due to the fact that it'll cause ambiguity in case there are multiple var-args, when the defined data type for both is same, but I'm not sure this is the correct reason behind it.)

I haven't used var-args in my code though, but yes I know their use. Still I'm unable to understand the reason behind above statements. Any help would be appreciated.

like image 588
gaurav jain Avatar asked Mar 15 '23 02:03

gaurav jain


1 Answers

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

That is just a limitation in the language specification. And yes, the reason for that is likely that it can become ambiguous very fast if you allowed more flexibility.

In the builder pattern, there is no such limitation, as every parameter can get its own method.

  builder
    .withOptions("a", "b", "c")   // varargs
    .withColors("red", "blue")    // more varargs
    .build();
like image 54
Thilo Avatar answered Mar 31 '23 06:03

Thilo