Search code examples
oopprivateencapsulationpublicaccess-modifiers

Access Modifiers - what's the purpose?


I'm relatively new to programming in general and I was wondering if anyone could help me understand the purpose of access modifiers? I understand the fact that they set different levels of access for classes and variables etc. but why would you want to limit what has access to these? What is the point in not allowing access for different things? why not just allow access for everything?

Sorry if this is a stupid question!


Solution

  • There are thousands of reasons, but I'll quote a few from here and then expand on those:


    Hiding the internals of the object protects its integrity by preventing users from setting the internal data of the component into an invalid or inconsistent state.

    It is very common for a type to enforce certain invariants (e.g., A person's ID number must always be 8 characters long). If a client has full access to every member of a class, then there's no way you can enforce those constraints. Here's a concrete example:

    public class Person
    {
        public string Id;
    
        public void SetId(string newId)
        {
            if(newId.Length != 8)
                throw new InvalidArgumentException("newId");
    
            Id = newId;
        }
    }
    

    There's nothing preventing me from just accessing the Id field and setting it to whatever I want! I could just do this:

    Person p = new Person();
    p.Id = "Invalid Id";
    

    That's why your private state needs to be private.


    A supposed benefit of encapsulation is that it can reduce system complexity, and thus increase robustness, by allowing the developer to limit the inter-dependencies between software component.

    Say I develop a class which has 40 methods - 35 of which are needed to wire up the internals of the class and to implement its functionality, and 5 of which are actually important to the client. Now I give you this class for you to use - you look at its public interface and you see 40 methods, most of which are completely irrelevant to you, and you ask me "What the hell is this spaghetti of code??"

    In order to make sure the intent of a type is clear, you restrain the access of any members that are not relevant to the client.

    Also, more public members = greater public surface = more stuff that needs to be tested = harder to maintain.


    As a rule of thumb, try to make your members as private as possible, and then work your way up from there. For example, start with private, and then:

    1. Do/would derived classes need to access this member? If so, promote to protected
    2. Do/would other classes need to access this member? If so, promote to public