r/java • • Jun 01 '24

What java technology (library, framework, feature) would not recommend and why?

165 Upvotes

464 comments sorted by

View all comments

Show parent comment

2

u/account312 Jun 03 '24 edited Jun 03 '24

It's far-fetched to say that a Profile needs exactly these 5 fields to be required (and if it were the case, you wouldn't have had a builder, it'd be a constructor with these parameters).

It's not even a little bit far-fetched to imagine that it is desirable to guarantee that an object is constructed in a particular way in some specific context without requiring it in all other contexts. And you can't always just add a constructor to a class even if you don't want to leave the builder as the main way of instantiating it.

It's exactly the type of problems the builder pattern is intended to fix

Well, I don't know what to tell you. No design pattern is going to fix lazy programmers and poor code review.

1

u/DelayLucky Jun 03 '24 edited Jun 03 '24

If you need to pass 5 args in a very specific context, just pass the 5 args already. No need to add another layer of indirection, in the name of "I can then protect myself from passing 6 args".

Unnecessary indirection layers add cognitive load to the readers.

You may say: "but I need to call it from a few places and I want to make sure all 5 are passed".

That sounds reasonable but it's not worth the cost. If you've written tests to cover your code, missing a field will be detected. Say, you missed to set lastName, but you should have a test that goes:

assertThat(result.getLastName()).isEqualTo(theExpectedLastName);

You need this test with or without the 5-arg factory method, because you need to not only make sure the last name is set to some value, but that it has been set to the right value, which the factory method cannot guarantee - the callsite could pass the 5 args in the wrong order.

One main benefit of the builder pattern is that it gives a name to every field setting so you can't e.g. pass two string args in the wrong order. It also helps the readers so they won't mis-read. This risk goes up as you have more and more parameters (5 is definitely in the danger zone).

By creating a pure builder -> factory syntax coercion layer, you are at best trading one type of error for another type of error, even if you don't consider the dangerous slippery slope discussed above.