Why Keep Variables Private?
The quick and short of variable privacy in OOP.
Join the DZone community and get the full member experience.Join For Free
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 nonsensical at first, since you are still able to access it with additional steps.
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?
If you make this variable public, someone who is using your class can set it to 13 or -5 or any number they wish, 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:
As you can 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.
Above, the pseudo-code shows a case where we need an accessor/getter method or function to protect our data from being 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.
Opinions expressed by DZone contributors are their own.