Why use a private?

Asked

Viewed 289 times

9

I’m learning variables public and private.

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

Even though I read a lot in theory, I still can’t understand in practice.

  • 2

    Another related: Access modifiers in C#

  • thanks for the tips. the theory I a notion, but had not thought of the duplicate names of the variables equal @diegofm spoke.

  • In fact, if it’s only you who encodes this software and it’s small and simple enough that you don’t depend on a well-designed interface to understand it, it doesn’t matter if you specify the member’s visibility; you’re right about that. But C# isn’t just made for small, simple software developed by a single person, right? In software that meets more complex needs, a well-defined interface helps a lot to understand the system.

1 answer

7


Because the philosophy of C# is to protect you from yourself, after all you can end up forgetting and accessing what you should not, especially after a time that created that code. Furthermore, who guarantees that only you will handle this code? Why use a convention if you can have a guarantee?

The philosophy of language is to encapsulate the implementation and expose only the contract. There is still ground to understand these things in detail, but there is a lot here on the site that you can search and ask if you still don’t have an answer. Example: What are the concepts of cohesion and coupling?

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

Also, with something marked as private, it is possible for the compiler to do some optimizations by knowing that it will never be called off.

Some design patterns may benefit from this feature.

We don’t program it to work, we program it to be all right. Developing software is quite complicated and we have to be as careful as possible.

This is a resource that helps better manage this complexity. In doubt you must protect yourself to the fullest and open as necessary.

If the question is about creating properties instead of variables, there has been answered in Property Vs variables.

Browser other questions tagged

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