What is the difference between the constructor method and the use of setters in Javascript object orientation?

Asked

Viewed 111 times

1

The question may seem a little crude, but I was left with doubts and I would like to understand more deeply.

The constructor feeds the created class objects, correct?

Doubts are:

  1. So what use is he if he has the setters which also feeds the object?

  2. I can work with a JS class only with the builder without the getters/setters or work without the builder getting the getters/setters?

  3. Somehow the doubt 2 will get in the way of something when it comes to making inheritance?

1 answer

1


About the builder has already been answered in: What good is a builder?.

In general it is a mistake to work only with getters/setters precisely from what is written in link above, but for everything there is exception. It is very common to work without setters because many objects must be immutable. There are cases that work without getters also for two reasons:

  • this idea of getter/Setter is considered wrong by many people who preach that it should have a method that has a more specific behavior and that by chance will change the state of the object, but that it should not have methods whose only function is to change the state of a member without doing anything else
  • in many cases create getter/Setter does not bring advantages and it is better to use the direct member (in JS they have always done this, but is spreading an idea of using it in other languages that are not Java, where they started to use it effusively, I consider it a mistake the indiscriminate use). People use this pattern without understanding why it exists and what problem it solves and if it really solves what it intends, people as soon as there is this rule and it should be used without question. Who knows how to program only uses them in cases where they are useful.

You can see more about this at several questions here.

The last item the answer is no.

  • I’ve researched it as well, and I’ve seen your response, and as far as I can tell, it goes according to need then. In Java for example, I learned to declare 2 constructs, one empty and the other to fill. In case you need to instantiate one or the other and have no problems. Already in PHP that I am studying now, there is only how to declare one, so when instantiating an object I will be obliged to pass the parameters via constructor, so I did not find it very interesting its use. Obviously it will depend on the need.

  • The empty constructor along with one another is largely a mistake. I think your constructor view is completely mistaken.

Browser other questions tagged

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