Consider builder when facing with many constructor -Effective Java Notes
When to use? we have many parameters in a class.
Some other methods(not good options)
Method 1: telescope constructors.
What: Write many constructors and each of them contains different number of parameters.
Why not good: It is not clean code. We have to maintain many constructors.
Methods 2. JavaBean methods.
What: lots of setters methods.
Why not good: Because construction is split across multiple calls, a JavaBean may be in an inconsistent state partway through its construction.
What does it mean by “invalid state”?
To understand this, first we should know what is the state.
In wikipedia, “In object-oriented programming, a class is an extensible program-code-template for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions or methods)”
In this way, the invalid state = invalid data. For example, an object should have 5 fields. But we forgot to set a field, or we set the wrong field. Another posible scenario is we changed the field value after the object was constructed in other place, this might also cause the invalid state problem. Then, this object is in “invalid state”. This kind of bug are really hard to find.
So I think the most important advantage is that, if we construct the objects by builder, then we can ensure our objects are imutable.
Nowadays, the functional programming is becoming a hot topic. A philosophy of functional programming is the objects should be immutable. That is after an object is created, it should not be changed. If you want another similar object that only has one difference, then create a new one.
3. Builder
What: Instead of making the desired object directly, the client calls a constructor (or static factory) with all of the required parameters and gets a builder object.
Why:
- the objects are immutable.
- It is easy to read and understand.
How to create the builder pattern?
- Create a public outer class with private constructor(parameter is builder) and private fields.
- Create the static builder class with private fields.
- Builder class has the build method which return the outer class.
The book Effective Java show a good example, you can also check the code on my github.
We don’t need to write the builders ourselves, with the lombok, just a simple annotation, they will generate the builders for us.
Reference: Effective Java

