Use builder pattern for methods with many parameters?

I've read a recommendation in "Effective Java" to use the Builder pattern when faced with constructors that use lots of parameters.

Does the same pattern apply to methods with lots of parameters ?

Jon Skeet
people
quotationmark

Yes, sort of. You basically create a new type to encapsulate all the parameters - or maybe just some of them.

Now you can create a builder and then an immutable version of the type - or you could just allow the "uber-parameter" type to be mutable and pass it directly in. In the latter case you don't have a builder pattern as such, but you can sort of view it as building the method call itself, in that you can specify each aspect of the method call separately. You could argue that the builder pattern is actually just a special case of this pattern, in some ways - it so happens that the build() method is usually on the builder rather than having the builder as a method parameter elsewhere, but there's a definite correlation between the way the two work.

An example of this in the .NET framework is XmlWriterSettings which is passed into a bunch of methods or constructors. (It's sort of used as a builder in that usually it's used when constructing an XmlWriter.) I can't think of any examples within the standard Java library right now, but they may exist somewhere...

If you do find yourself with lots of parameters though, it's worth taking another look at the design to check whether you shouldn't be grouping some of them together anyway, just as part of normal design.

people

See more on this question at Stackoverflow