Part 4 of 6 · 1 min read
Costs
Extra code, so use it where it pays.
EJ lists the costs. A builder must be created before the object, which is a small price that can matter only in performance-critical code. A builder is also more verbose than a constructor. EJ suggests using it when there are enough parameters to justify it, say four or more, especially when many are optional or have the same type. It adds that a class often grows more parameters over time, so starting with a builder can be better than switching later and leaving old constructors behind.
EJ also points out some strengths. One builder can be used repeatedly to make several objects, changing a setting between calls. A builder can fill in values automatically, such as a serial number that rises with each object. And the builder pattern fits class hierarchies, with a parallel hierarchy of builders.
Modern Java has other tools for the same job. A record is good for a few required fields. Named static factories (module 1) are good for a few variants. Use a builder when the options are many and mostly optional.
A rule of thumb for LLD rounds: when you draw a class with more than four fields and some optional ones, say "I would construct this with a builder so it can be immutable and validated".
Common mistake
Building a builder for a class with two fields. The extra code adds noise, and a plain constructor or a static factory reads better.
Check yourself: 1. At roughly how many parameters does EJ suggest a builder pays off? 2. Name two strengths of a builder besides readability.