Question

I read this question on how to split large constructors in java. But I am not quite sure what I shall do in my case. The question suggests that a builder pattern is the better way to go but at the same time one person in some sub sentence said "only if some parameters are optional". Because all my parameters are mandatory I don't see any advantage of a builder pattern. I would only risk forgetting to pass an important peace of information. Is therefore my only option to create new logical grouped objects or am I missing some vital fact on the builder pattern? Builders only seem to be good if stuff can be missing?

Était-ce utile?

La solution

"Is therefore my only option to create new logical grouped objects or am I missing some vital fact on the builder pattern?"

My Opinion is :

Yes. Using builder in this case provides no additional benefit compared to the amount of work required in the abstraction.

Also mentioned in the comments: if you've got too many parameters for an object, maybe the object is doing too much.

Autres conseils

Even if all your parameters are mandatory, the builder pattern still has a few advantages:

  1. It more readable. If your constructor has ten parameters, it is hard to remember which is which is which, especially if a lot of them are 0 or null.

  2. The builder can be passed around to several different methods to accumulate the data it needs. This is useful if some of that data exists in one class and some in another.

  3. If some of your parameters are lists or other collections that need to be assembled before being handed off to the constructor, a builder can take care of that internally. They can also eliminate some of the need for defensive copies, since the builder knows that it doesn't leak any of those objects.

  4. A builder can serve as a serialization proxy, giving you more control over the serialized form or the JAXB XML form of your object.

That said, my approach would always be to start with a plain constructor, and introduce a builder only if calling that constructor is causing a lot of mess in your code and the extra clarity added by the builder is enough to justify adding a whole new class.

Many parameters to the constructor may also be a sign of too many concerns the class is dealing with. Builders only make sense when there are cascaded cases: for boys add a rude language section, for girls a shopping list.

Splitting the concerns depends: either inheritance, generic parametrized classes, delegating classes, and yes heavier logical grouped objects.

Consider also whether you can write a test case. Test driven development is helpful here. If you then need to mock a parameter class, "dependency injection" would require a more abstract parameter class.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top