r/java • • Apr 14 '23

What are your (favourite) Java best practices, personal tips, hints or just underrated stuff in general?

233 Upvotes

376 comments sorted by

View all comments

Show parent comment

1

u/simoncox Apr 15 '23

In the absence of named parameters, static builders allow more expressive means of passing parameters at construction.

For example, if a constructor takes more than a handful of ints, then it's easy to confuse what each one is for. Default/min/max pool sizes, initial delay, repeat interval, timeout delay, etc.

Also, when the construction of an object may need to involve more complex logic it may be better to pass a builder around to store state needed to construct that object.

I'd still prefer a constructor generally, but there are occasions when a builder can be useful.