Question

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 ?

Was it helpful?

Solution

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.

OTHER TIPS

Not exactly, because what Builder does is building an object.

So what would be the point of changing some method, which does who knows what, into a Builder?

What you should do with methods containing too many arguments is for example:

  • break it down to smaller methods,
  • use varargs
  • use some Collection to put into the same type arguments

Turning a method into a builder is possible but atypical. Apache HashCodeBuilder is one example, used like int hash = new HashCodeBuilder().append(a).append(b).build();, although in that specific case you might prefer to just use a method with varargs, like Guava's Objects.hashCode, used like int hash = Objects.hashCode(a, b);.

A method which takes a large number of arguments of different types is ill-suited to varargs, so you might find a builder appropriate, or you might want to consider reducing the amount of work that is being done in that method, or encapsulating the arguments in some other composite type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top