Advanced Lesson 3
Advanced Object-Oriented Programming
Chapter 3: Encapsulation
Encapsulation
In this chapter, we will discuss the remaining ‘pillar’ of OOP known as encapsulation.
In our discussions so far, we have been assuming that all attributes of a class instance can be directly accessed and modified by any other object.
But should our objects really expose everything, including their internal states, for the whole world to see and manipulate?
As an example, let’s look at our RPG Hero
class from our core lessons. If you recall, a Hero
has a health
attribute and an attack
attribute. Anybody can directly change their values. So we can have our EvilBoss
below directly setting our hero’s health
and attack
to zero. So EvilBoss
is basically just asking the character to drop dead without even fighting, and your Hero
is obliged to do so since it has given everyone direct access to those attributes.
class EvilBoss:
def destroy(self, hero):
hero.health = 0
hero.attack = 0
Therefore, there are times in OOP when you do not want to expose your attributes directly. For example, you might not want someone else to modify your attributes directly (maybe you want to ensure that the values are legal). Or you want to embellish your attributes before allowing someone to access it (i.e. putting on some makeup). Sort of like you putting on a face mask before going out, in case someone passes a certain virus to you! Therefore, you should not make these attributes publicly accessible to others. This is what encapsulation is - only exposing what is necessary, and hiding things that are not!