Encapsulation
While working with classes and dealing with sensitive data, implementing global access to all the variables used within the program code is not a good choice because then the chances of data being tampered with will increase. For this purpose, Object-Oriented Programming languages have the concept of Encapsulation.
Encapsulation ensures that the outside view of the object is clearly separated from the inside view of the object by hiding the implementation of operations and state from the interface, which is available to all other objects.
What is Encapsulation?
Encapsulation is:
- Binding the data with the code that manipulates it.
- Keeping the data and the code safe from external interference.
A common analogy to understand encapsulation is when you visit a restaurant. The waiter comes to take your order and delegates the preparation to the chef. You, as a customer, do not directly interact with the chef. Similarly, in programming, encapsulation ensures that objects communicate with one another via well-defined methods, rather than allowing direct access to internal details.
This helps in:
- Improved control over input data.
- Enhanced security.
- Reduced vulnerability of data tampering.
- Building loosely coupled code.
Examples of Encapsulation in R Programming
Example 1
# Creating a list
car <- list(model_name = "Sedan",
engine = "Diesel",
max_speed = 180)
# Assigning a class to the list
class(car) <- "Vehicle"
# Printing the object of class 'Vehicle'
car
Output:
$model_name
[1] "Sedan"
$engine
[1] "Diesel"
$max_speed
[1] 180
attr(,"class")
[1] "Vehicle"
Example:
# Creating a list
location <- list(city = "Mumbai",
state = "Maharashtra",
pincode = 400001)
# Assigning a class to the list
class(location) <- "Address"
# Printing the object of class 'Address'
location
Output:
$city
[1] "Mumbai"
$state
[1] "Maharashtra"
$pincode
[1] 400001
attr(,"class")
[1] "Address"
Key Takeaways
When using encapsulated code like the above examples, keep the following points in mind:
- Ease of Access: Everyone knows how to access the encapsulated object.
- Abstraction: Can be easily used regardless of the implementation details.
- No Side Effects: Encapsulation ensures there are no unintended effects on the rest of the application.
Encapsulation also aids in creating more maintainable code, blocking the ripple effects of code changes, and helping to build loosely coupled systems by minimizing direct access to an object’s internal state and behavior.
Leave a Reply