There’s an earthquake in Canada :)
If it’s necessary and you know what you’re doing, it’s okay. Of course, this example can be a problem because a balance should not be manipulated directly. I don’t even know if a client should have a balance and a method Sacar()
. I know it may be just an example, but it induces something wrong.
But don’t think it gives any security. If a programmer wants to change a value he will change. Encapsulation only protects the well-meaning programmer who does not want to risk making a mistake by accessing the field directly. It is something that the compiler "prevents" access, but from then on anything can happen.
It’s more a matter of code organization, something that helps manage the complexity of objects and pass the right intention. It has to do with encapsulation.
In this way it helps achieve cohesion and avoid coupling unintentional.
Actually there’s a worse problem in this code that is storing monetary value in a double
.
I’m not a fan of the term attribute for this, I prefer field.
See more:
If "someone" is another application class, that’s right.
– bfavaretto
Already have an answer on the site about encapsulations! I just could not find
– novic
https://answall.com/questions/15467/m%C3%A9todos-e-propriedades-em-c-vantagens-e-desvantagens @bfavaretto ou essa, imagine you already have some !!! ;)
– novic
Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).
– Maniero