“assorted-color container lot” by Jisu Han on Unsplash

Why do we need private variables?

Cristina Tarantino
Published in
5 min readOct 4, 2018

--

When learning a new language I often find myself wonder about the visibility of attributes and methods in a class (if learning a OO Language).

So I asked myself why? What is so important about the accessibility of members of a class in a language.

Let’s start with a metaphor.

Suppose a doctor gives a patient 3 different medication powders. The doctor tells the patient that every time they take their medication, they are supposed to mix 3 mg of white, 2 mg of red and 4 mg of green powder, combine them and then take them with a glass of water.

As well as the hassle of having to repeat the process each time there is also a bigger issue: you need to trust that your instruments and your measurement skills are precise enough each time to produce a mix that would not be harmful.

One way to solve this issue is for the pharmacist to create a simple ‘Capsule’ that contains the right mix of medications as prescribed by the doctor. Now the patient knows that what is actually inside the capsule is correct and they can avoid the hassle of measuring the content, thereby avoiding the risks associated with the process of mixing medications.

So using a ‘Capsule’ is convenient for the patient and allows them to trust that the medication will treat their problem.

Translating this metaphor into the Software Engineering world we often find a concept in Object Oriented Programming called Encapsulation.

This concept is one of the most crucial best practices when coding. The reason being that it makes our code:

  • secure
  • easily maintainable
  • usable

Lets get coding to show what I mean:

class MedicineCapsule:
def __init__(self, white, red, green):
self.white = white
self.red = red
self.green = green

pill = MedicineCapsule(3, 2, 4)

In the above case the user of the MedicineCapsule class has to know that to use the prescribed pill he needs to have mix:

  • 3mg of white powder
  • 2mg of red powder
  • 4mg of green powder

to obtain the prescribed medicine.

Say one day the user forgets the precise recipe he could also type:

day2_pill = MedicineCapsule(3, 5, 4)

resulting in an incorrect dosage making the second day pill dangerous.

Now to avoid this we could change the code:

class MedicineCapsule:
white = 3
red = 2
green = 4

def composition(self):
print("My composition is:\n %s white powder\n %s red powder\n %s green powder" % (self.white, self.red, self.green))

pill = MedicineCapsule()
pill.composition()

# input

# My composition is:
# 3 white powder
# 2 red powder
# 4 green powder

Now this prevents the end user having to remember the Medicine recipe every time allowing them to concentrate on how to solve their problem.

Now lets get to the visibility issue. The code above still allows the end user to access and change the medicine’s composition making the pill potentially dangerous.

pill.white = 5
pill.composition()

# input
# My composition is:
# 5 white powder
# 2 red powder
# 4 green powder

Python does not offer a way to avoid this. As the documentation says:

“Private” instance variables that cannot be accessed except from inside an object don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.
9. Classes — Python 3.7.0 documentation

As an experienced Python developer reminded me recently:

Python assumes users of a class are grown ups.

I started my career as a Java developer and the reason why I always ask about encapsulation and visibility is because in Java you can prevent the end user from manipulating private members. Let’s give an example:

public class MedicineCapsule 
{
private int white = 3;
private int red = 2;
private int green = 4;

public String composition()
{
return "My composition is:\n" + this.white + " white powder\n" + this.red + " red powder\n" + this.green + " green powder";
}
}

public class MainClass
{
// arguments are passed using the text field below this editor
public static void main(String[] args)
{
MedicineCapsule pill = new MedicineCapsule();
System.out.print(pill.composition());
}
}

//input

// My composition is:
// 3 white powder
// 2 red powder
// 4 green powder

Now if you try to override in the main the value of the white powder by doing:

public class MainClass 
{
// arguments are passed using the text field below this editor
public static void main(String[] args)
{
MedicineCapsule pill = new MedicineCapsule();
pill.white = 5;
System.out.print(pill.composition());
}
}

You will get an error like:

MainClass.java:15: error: white has private access in MedicineCapsule
pill.white = 5;
^
1 error

Now Java provides so called “access specifiers” and actually delivers protections to class members.

Other languages like Python use conventions to deliver the same concept. Languages like Solidity offer “access specifiers” to express the same concept but in reality do not deliver effective protection (Your “private” Solidity Variable is Not “private.” Save it before it becomes Public).

JavaScript does not offer encapsulation out of the box but there a numerous ways to implement encapsulation. There is a proposal for ES8 to implement this functionality but it will take time to be fully supported by browsers. (Stay tuned as I will be talking in my next article about this).

Last but not least. Say new researches have showed that by adding a new powder and tweaking the medication composition the patient has a more effective treatment. If we didn’t have encapsulation we would have to go through every line of our code where we initialised the pill object and change the line pill = MedicineCapsule(3, 2, 4) with pill = MedicineCapsule(3, 2, 5, 1). By using encapsulation we only need to change one file, the one containing our MedicineCapsule class and the rest of our code would not know or even need to know we have changed composition and effectively solved the user of the class problem more effectively.

So just to recap those are the three main points that Encapsulation offers:

  • protection or data hiding for the class members from being directly accessed (more effective if the language provides access specifiers that effectively prevent hiding of class members);
  • abstraction by providing features without giving implementation details; the user of the class knows only what is needed to solve their problem;
  • maintainability by helping to prevent the ripple effect of code changes.

--

--