Why Private Variables are Needed in Object-Oriented Programming – Encapsulation

encapsulationobject-oriented

Why do we need private variables in classes?

Every book on programming I've read says this is a private variable, this is how you define it but stops there.

The wording of these explanations always seemed to me like we really have a crisis of trust in our profession. The explanations always sounded like other programmers are out to mess up our code. Yet, there are many programming languages that do not have private variables.

  1. What do private variables help prevent?

  2. How do you decide if a particular property should be private or
    not? If by default every field SHOULD be private then why are there
    public data members in a class?

  3. Under what circumstances should a variable be made public?

Best Answer

It's not so much a matter of trust, but rather one of managing complexity.

A public member can be accessed from outside the class, which for practical considerations means "potentially anywhere". If something goes wrong with a public field, the culprit can be anywhere, and so in order to track down the bug, you may have to look at quite a lot of code.

A private member, by contrast, can only be accessed from inside the same class, so if something goes wrong with that, there is usually only one source file to look at. If you have a million lines of code in your project, but your classes are kept small, this can reduce your bug tracking effort by a factor of 1000.

Another advantage is related to the concept of 'coupling'. A public member m of a class A that is used by another class B introduces a dependency: if you change m in A, you also have to check usages of m in B. Worse yet, nothing in class A tells you where m is being used, so again you have to search through the entire codebase; if it's a library you're writing, you even have to make sure code outside your project doesn't break because of your change. In practice, libraries tend to stick with their original method signatures as long as possible, no matter how painful, and then introduce a block of breaking changes with a major version update. With private members, by contrast, you can exclude dependencies right away - they can't be accessed from outside, so all dependencies are contained inside the class.

In this context, "other programmers" include your future and past selves. Chances are you know now that you shouldn't do this thing X with your variable Y, but you're bound to have forgotten three months down the road when a customer urgently needs you to implement some feature, and you wonder why doing X breaks Y in obscure ways.

So, as to when you should make things private: I'd say make everything private by default, and then expose only those parts that absolutely have to be public. The more you can make private, the better.

Related Topic