Vishal
Vishal

Reputation: 21

Using Parameterized constructors(with mandatory fields) and setters instead of Using Builder Design Pattern

When we have a class with lots of fields out of which some are mandatory and some are optional, then it is a bad practice to use Constructors because of several issues, one being poor readability. Builder Design Pattern could be one solution where we separate the construction logic and use a step-by-step approach to create an Object. My question is:

1.)Why can't we Setters in combination with a parameterized constructor which will contain mandatory fields instead of Builder Pattern? The optional fields can be set using setters.

2.) Why should we use the Builder Design Pattern over Setters with the parameterized constructor? One reason I could think of is Immutability. What other benefits does it have?

3.)If we don't want immutability, then is it justifiable to use setters with Parameterized constructors instead of the Builder Pattern?

Upvotes: 1

Views: 201

Answers (1)

Stephen C
Stephen C

Reputation: 718886

1.) Why can't we use setters in combination with a parameterized constructor which will contain mandatory fields instead of Builder Pattern? The optional fields can be set using setters.

Well you can do this. But consider this.

In the builder pattern, you make a series of calls to set parameters and then call build(). The build() call checks the settings and then creates and configures and initializes the instances.

You could do the same thing as a constructor call followed by a series of setter calls and an init call. However:

  • Code outside of the class needs to see the setters and the init method and it must follow the "protocol".

  • The code in the class that deals with the initialization, etc needs to be more robust. For example, if an instance is used before it is initialized, or if an notionally immutable attribute is changed after the initialization, then exceptions need to be thrown.

2.) Why should we use the Builder Design Pattern over Setters with the parameterized constructor? One reason I could think of is Immutability. What other benefits does it have?

See above. The builder pattern is a way to abstract the construction protocol. It reduces unwanted coupling.

3.) If we don't want immutability, then is it justifiable to use setters with Parameterized constructors instead of the Builder Pattern?

Yes. See above for a justification.

Naturally, the strength of this justification depends on how complex the initialization protocol is, and how beneficial it is to abstract it away from code that uses the class.

Upvotes: 2

Related Questions