When and why to use a parameterized constructor?

Asked

Viewed 283 times

3

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

1 answer

4

The purpose of the constructor is, as the name says, to build the object. Therefore, when the constructor 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 using an empty constructor, it provides a skeleton of an object that in its state is not usable, and then uses a lot of setters to fix that skeleton. The responsibility to build the object should be the constructor’s, but if he does not, this responsibility will eventually have to be carried out somewhere else, violating the principle of single 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.

Let the constructor return an incomplete object to be repaired after calling up a lot of setters is a anti-standard. 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 of bugs and it becomes more difficult to read, write, understand and change the code if needed.

Moreover, the fact that the constructor gives up on constructing the object properly, 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.

  • So it is right to build an object with the parameterized constructor. Because, the default makes an object inconsistent, which plays the responsibility of assigning values to the object in September. I’m right?

  • 1

    @Exact Gilmarsantos.

  • I will only use setters if an attribute changes status during code execution?

  • 1

    @Gilmarsantos Yes. The idea is that the Setter will mutate the object, ideally from one consistent state to another consistent state. If Setter is inadequately called trying to make the object inconsistent, an exception is made. Just as making the object be born inconsistent to be fixed later is bad, allowing Setter to make it inconsistent is also. Also, you only publish setters for what makes sense to mutate.

  • 2

    It is interesting to note that in Java, creating a non-standard constructor (with parameters) disables the default auto constructor. This is legal because it reinforces this idea of not letting the object be created inconsistent.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.