When and why to use a parameterized constructor?

3

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

    
asked by anonymous 14.10.2017 / 06:26

1 answer

4

The purpose of the constructor is, as the name says, to construct the object. So, when the counter returns, the object that is provided 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 the state that it is not usable, and then a lot of setters are used to fix that skeleton. The responsibility for constructing the object should be for the constructor, but if he does not do so, that responsibility will eventually have to be performed elsewhere, in violation of the principle of sole responsibility .

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

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

In addition, the fact that the builder does not properly build the object, almost obliges the programmer to put setters for everything, even for what should be given and internal behaviors of the object, leading to a violation of the encapsulation. / p>     

14.10.2017 / 06:35