What happens in real life in a developer environment if the programmer does not encapsulate an attribute? [duplicate]

3

The programmer John went there and created a Cliente class and the public double saldo attribute and the Sacar() public method as well.

What is the problem with leaving the double saldo attribute, what would be the problem if John did not deprive the balance attribute?

I can only imagine that someone could choose some random customer and increase a person's balance and you?

class Cliente 
{    
    public decimal saldo;
    public void Sacar()
    {

    }
}
    
asked by anonymous 12.05.2017 / 23:36

1 answer

5

There is an earthquake in Canada:)

If you need to and you know what you're doing, that's okay. Of course this example can be a problem because a balance should not be manipulated directly. I do not even know if a client should have a balance and a Sacar() method. I know it may just be an example, but it induces something wrong.

But do not think it gives you any security. If a programmer wants to change a value it will change. The encapsulation only protects the well-intended programmer who does not want to run the risk of making an error by accessing the attribute directly. It is something that the compiler "prevents" access, but everything can happen from now on.

It's more a matter of code organization, something that helps you manage the complexity of objects and pass on the right intent. It has to do with encapsulation .

This helps achieve cohesion and prevents unintentional coupling .

You actually have a worse problem with 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:

12.05.2017 / 23:44