Search code examples
privatepublic

A pragmatic view on private vs public


I've always wondered on the topic of public, protected and private properties. My memory can easily recall times when I had to hack somebody's code, and having the hacked-upon class variables declared as private was always upsetting.

Also, there were (more) times I've written a class myself, and had never recognized any potential gain of privatizing the property. I should note here that using public vars is not in my habit: I adhere to the principles of OOP by utilizing getters and setters.

So, what's the whole point in these restrictions?


Solution

  • The use of private and public is called Encapsulation. It is the simple insight that a software package (class or module) needs an inside and an outside.

    The outside (public) is your contract with the rest of the world. You should try to keep it simple, coherent, obvious, foolproof and, very important, stable.

    If you are interested in good software design the rule simply is: make all data private, and make methods only public when they need to be.

    The principle for hiding the data is that the sum of all fields in a class define the objects state. For a well written class, each object should be responsible for keeping a valid state. If part of the state is public, the class can never give such guarantees.

    A small example, suppose we have:

    class MyDate
    { 
        public int y, m, d;
        public void AdvanceDays(int n) { ... } // complicated month/year overflow
        // other utility methods
    };
    

    You cannot prevent a user of the class to ignore AdvanceDays() and simply do:

    date.d = date.d + 1; // next day
    

    But if you make y, m, d private and test all your MyDate methods, you can guarantee that there will only be valid dates in the system.