When and why use a parameterized constructor?

I'm very confused. I wonder if it is better to use the default and the setters to assign a value to the attribute, or if it is better to assign the values to the attributes via the parameterized constructors and use the setters to change their states.

Author: Gilmar Santos, 2017-10-14

1 answers

The purpose of the constructor is, as the name says, to construct the object. Therefore, when the constructor returns, the object that is supplied should already be ready for use.

An object is properly constructed when all its attributes are set to a value that represents what the object is.

However, when an empty Constructor is used, it provides a skeleton of an object that in its current state is not usable, and then uses a bunch of setters to fix that skeleton. The responsibility for building the object should be the constructor's, but if he does not, that responsibility will end up having to be carried out somewhere else, violating the principle of sole responsibility .

The result of this is a form of sequential coupling. That is, the object is only usable if certain methods are called on it.

Let the constructor return an incomplete object to be fixed after calling up a bunch of setters is an anti-default . Avoid doing this. Objects built like this are harder to stay consistent, since the constructor already manufactures them inconsistent. This means that there are greater possibilities for bugs and it becomes more difficult to read, write, understand and change the code if necessary.

Also, the fact that the constructor gives up properly constructing the object, practically forces the programmer to put setters for everything, even for what should be data and internal behaviors of the object, leading to a violation of encapsulation.

 4
Author: Victor Stafusa, 2017-10-14 04:55:50