Search code examples
c++oopabstractiongetter-setterdata-access

Should I use public or private variables?


I am doing a large project for the first time. I have lots of classes and some of them have public variables, some have private variables with setter and getter methods and same have both types.

I decided to rewrite this code to use primarily only one type. But I don't know which I should use (variables which are used only for methods in the same object are always private and are not subject of this question).

I know the theory what public and private means, but what is used in the real world and why?


Solution

  • private data members are generally considered good because they provide encapsulation.

    Providing getters and setters for them breaks that encapsulation, but it's still better than public data members because there's only once access point to that data.

    You'll notice this during debugging. If it's private, you know you can only modify the variable inside the class. If it's public, you'll have to search the whole code-base for where it might be modified.

    As much as possible, ban getters/setters and make properties private. This follows the principle of information hiding - you shouldn't care about what properties a class has. It should be self-contained. Of course, in practice this isn't feasible, and if it is, a design that follows this will be more cluttered and harder to maintain than one that doesn't.

    This is of course a rule of thumb - for example, I'd just use a struct (equivalent with a class with public access) for, say, a simple point class:

    struct Point2D
    {
       double x;
       double y;
    };