Object Oriented Concepts: Encapsulation

Book definition of Encapsulation is : “Binding of Data as well as Methods to a single unit”, What does it mean?

Imagine you are building an online Job Portal and you accept parameters like Name of the User, Age and other demographics. The adds his/her information in your system:

{
  id = 1
  first_name = "Dimple" 
  last_name = "Mathew"
  age = -1
}

Here we are creating a user with id=1 and other attributes like name and age, but there is a problem – we are changing the state of object directly i.e.. when user creates a profile he/she would directly assign these value and save to our database.

In a production ready application we will need to handle all these edge cases so that we have the data that we require in our database.

How can Encapsulation help?

So with encapsulation in place, the client/user will not be able to change the data in the object directly.

Here in the following example we added some getter and setter functions to set the age and validate it.

Getters gets the value and Setters set the value of the data member

""" Encapsulation example"""

class JobPortal:

    def __init__(self):
        self._age = None

    def set_age(self, age):
        """ Age setter method that sets the age of the user and validates    it"""
        if age < 0:
            raise Exception("Please enter a valid age")
        self._age = age

    def get_age(self):
        """ Age getter function that gets the age of the user and returns it """
        return self._age


if __name__ == "__main__":
    obj = JobPortal()
    obj.set_age(-2)
    print(obj.get_age())

Encapsulation helps us to hide the state object in the class preventing unauthorized or direct access to it.

Hope this was helpful

Stay tuned for more on Object Oriented Concepts

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s