Introduction to Encapsulation in Ruby
Introduction to Encapsulation
Welcome back! We're now shifting our focus to another essential concept in Object-Oriented Programming (OOP): encapsulation. Encapsulation helps us bundle the data (variables) and the methods that operate on the data into a single unit called a class. It also helps restrict access to some of the object's components.
What You'll Learn
In this lesson, you will learn how to:
- Define and use encapsulation: This involves hiding the internal state of an object and requiring all interaction to be performed through an object's methods.
- Create getter and setter methods: These methods allow controlled access to the object's properties using Ruby's
attr_accessor,attr_reader, andattr_writermethods.
Let's look at the following Ruby example to gain a better understanding:
In this example, we have a Person class with private data members @name and @age. The attr_accessor method automatically creates getter and setter methods, like name= and age=, for manipulating and accessing these private members.
In contrast if we use attr_reader or attr_writer, we can only create getter or setter methods, respectively. Here's an example:
In this example, we can only read the name and age properties of the Person object, but we can't modify them. If we try to set the name property, we'll get an error because the setter method is not available.
Similarly, if we use attr_writer, we can only create setter methods for the properties. Here's an example:
If we skip using attr_accessor, attr_reader, or attr_writer, and directly access instance variables, we lose control over the data and can't enforce constraints or validations. Encapsulation allows us to protect the object's internal state and provide controlled access to it.
