Search code examples
oopencapsulationaccess-modifiers

Who do we protect our classes from?


I'm currently learning C# and I was wondering, what is the point of declaring classes / methods private? Who are we hiding / limiting access to these classes.

Because if someone was editing the source they could just change the tag from private to public. I'm not sure how a user will be able to access these methods and what problems it would cause.

tldr; What's the point of access modifiers.


Solution

  • Member visibility, as this feature is often called, is not a security feature. It is a convenience for the programmer, designed to help limit cross-class dependencies. By declaring a member private, you prevent other code from accessing it directly. This has two advantages:

    • if you find that a member variable gets manipulated in a way you did not intend, the amount of code you have to check is significantly smaller when the variable is private
    • you can change the inner workings of a class (everything that is declared private) without breaking the interface (everything declared public)

    Member visibility is probably the most important language feature in realizing encapsulation, one of the core principles of object-oriented programming.