Why use private?

6

I'm learning variables public and private .

If I create all the program code, what is the need to create a private variable? Being that enough I do not program a code that accesses the same one of another class.

While reading a lot in theory, I still can not understand it in practice.

    
asked by anonymous 14.11.2016 / 21:26

1 answer

5

Because the philosophy of C # is to protect you from yourself, after all you may end up forgetting and accessing what you should not, especially after a while. What's more, who guarantees that only you will get into this code? Why use a convention if you can have a warranty?

The philosophy of language is to encapsulate the implementation and expose only the contract. You still have floor to understand these things in detail, but there is plenty of stuff here on the site that you can search for and ask if you still do not have a response. Example: What are the concepts of cohesion and coupling?

Hiding the implementation detail makes it easier to improve code without breaking the external compatibility.

In addition, with something marked as private, it is possible for the compiler to make some optimizations by knowing that it will never be called out.

Some design patterns may benefit from this feature.

We do not program to work, we program to be all right. Developing software is quite complicated and we have to be as careful as possible. This is a feature that helps manage this complexity . In doubt, you should protect yourself as much as possible and open as needed.

If the question is about creating properties instead of variables, it has already been answered here in Vs Variables property .

    
14.11.2016 / 21:42