Why Keep Variables Private?

DZone 's Guide to

Why Keep Variables Private?

The quick and short of variable privacy in OOP.

· Web Dev Zone ·
Free Resource


It’s suggested that no variable should be public in OOD. If you make your variable private, in order to access the data for reading or updating, you need getters and setters, but this seems nonsense at first since you are still able to access it with additional bureaucracy.

I would like to give an example to explain. Let's say you have a month variable which is an integer. This month variable should hold a value between 1 and 12 inclusively, right?

int month;

If you make this variable public, someone who is using your class can set it to 13, or -5 or any number he/she/ wishes, right? But, if you make it private you can force the update process to be performed via a function; now, you can enforce that the value passed into that function must be between 1–12 inclusive.

You may also like: 10 Commandments of Object-Oriented Design.

Look at the code below:

void setMonth(int newMonth){
if(newMonth < 1 || newMonth > 12)
return; // don't set it, you can throw an exception as well
month = newMonth;

As you see in the code, you have one layer where you can control the value before assigning it into your month variable. Isn't that cool?

You may ask a second question, "Why do I need an accessor or getter method/ function?"

I will give you another scenario. Assume you have a social security number variable for a bank application, and you want to disclose the last four digits if the user's role is a clerk, or fully show the number if the user's role is a manager.

string aSSN; // assume this is a private variable

string getSSN(){
if(role == CLERK)
return last four digits of aSSN;
if(role == MANAGER)
return aSSN; // full SSN 
return "You don't have credentials to see this info"; 
    //better throw an exception

Above, the pseudo-code shows a case where we need an accessor/getter method or function to protect our data to be accessed by others. There are other cases, but as in the Pareto principle, this covers 80% of the concepts for why we need getters and setters and variable privacy.

Further Reading

c, c++, encapsulation, ood, oop, programming, tutorial, variable hiding

Published at DZone with permission of Murat Gungor . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}