I've been reading about the Go4 "builder pattern". You can read more about that pattern here: https://www.sohamkamani.com/javascript/builder-pattern/
I don't understand why we can't just pass many params in a single param object like this
constructor({ name, age, address, phoneNum, email }) {
this.name = name;
this.age = age;
this. address = address;
this.phoneNum = phoneNum;
this.email = email;
}
In my eyes, this is far easier than creating a builder class.
Am I missing something?
yeah, you are right, it is possible to use just only parameters.
Having known that best practice is to use less number of parameters for methods to improve readability, it is better to use Builder
to create different representations of some object (for example, stone and wooden houses) by using the explicit names of methods.
Moreover, Builder
pattern solves the following problem:
Use the Builder pattern to get rid of a “telescoping constructor”.
Say you have a constructor with ten optional parameters. Calling such a beast is very inconvenient; therefore, you overload the constructor and create several shorter versions with fewer parameters. These constructors still refer to the main one, passing some default values into any omitted parameters.
class Pizza {
Pizza(int size) { ... }
Pizza(int size, boolean cheese) { ... }
Pizza(int size, boolean cheese, boolean pepperoni) { ... }
// ...
The Builder pattern lets you build objects step by step, using only those steps that you really need. After implementing the pattern, you don’t have to cram dozens of parameters into your constructors anymore.