Rami
Rami

Reputation: 67

Is it a good to practice to have a long constructor in Java?

this is from a new to the domain! thinking of an app to deal with an employee database in the university, an object employee should have at least 15 data points that need to be entered at object creation... is it normal to add all parameters in one constructor?

If no what are the alternatives?

Upvotes: 3

Views: 422

Answers (1)

user11595728
user11595728

Reputation:

Item 2 of Effective Java, 3rd Edition (Bloch) is:

Consider a builder when faced with many constructor parameters

However, the introductory sentence to the item clarifies a subtle point: constructors with many optional parameters are especially bad.

Static factories and constructors share a limitation: they do not scale well to large numbers of optional parameters.

In the text Bloch discusses two common alternatives to the Builder pattern:

  • Telescoping constructor pattern (overloaded versions of the constructor with different configurations of the optional parameters);
  • The JavaBean pattern (parameterless constructor and setter methods).

The long and short of it that the Builder pattern is preferred.

Upvotes: 10

Related Questions