D
D
DollyPapper2021-07-24 20:39:00
OOP
DollyPapper, 2021-07-24 20:39:00

Do constructors break encapsulation?

Good afternoon. The question is actually this. When passing initial parameters to a class, we usually store these values ​​in its properties. That is, in fact, the constructor is such a kind of setter for class fields. In my opinion this is a clear violation of encapsulation. Or not? After all, setters are scolded precisely because we can directly change the fields of an object, interfering with its structure from the outside. But in the constructor, we do the same. Yes, after creating an object in the absence of setters, we can no longer directly change the fields, but once during creation this happens, and we reveal the internal structure of our object. Where does this very line pass, where encapsulation is violated, and where not. The question is rather from the category of philosophy, but it is interesting who thinks what.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Sokharev, 2021-07-24
@DollyPapper

1. Setters do not break encapsulation.
If you are setting a property via a setter, are you even sure that it is stored in a property with the same name of the same class?
object.setProperty(value)
Here I am, looking outside at all xs where and how this property is stored, if at all. And you?
2. The constructor does not violate encapsulation. Exactly for the same reasons.
For obvious reasons, you should not have setters for everything, but only those that you want to change from the outside. If you have setters for everything in a row, then you are violating encapsulation. Setters have nothing to do with it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question