Open In App

Perl | Encapsulation in OOPs

Improve
Improve
Like Article
Like
Save
Share
Report

Encapsulation in Perl is the process of wrapping up of data to protect it from the outside sources which need not have access to that part of the code. Encapsulation is a part of the Object-oriented programming, it is used to bind the data and the subroutines that are used to manipulate that data. In a different way, encapsulation is a protective shield that prevents the data from being accessed by the code outside this shield.

  • Technically in encapsulation, the variables or data of a class is hidden from any other class and can be accessed only through any member function of own class in which they are declared.
  • As in encapsulation, the data in a class is hidden from other classes, so it is also known as data-hiding.
  • Encapsulation can be achieved by: Declaring all the variables in the class as local and fetching methods of the class by importing packages to set and get the values of variables.

Consider a real-life example of encapsulation, in a company, there are different sections like the accounts section, finance section, sales section, etc. The finance section handles all the financial transactions and keeps records of all the data related to finance. Similarly, the sales section handles all the sales related activities and keep records of all the sales. Now there may arise a situation when for some reason an official from the finance section needs all the data about sales in a particular month. In this case, he is not allowed to directly access the data of the sales section. He will first have to contact some other officer in the sales section and then request him to give the particular data. This is what encapsulation is. Here the data of the sales section and the employees that can manipulate them are wrapped under a single name “sales section”. Example: 

Perl




# Declaration and definition of Base class
use strict;
use warnings;
  
package Student;
sub new
{
   
    # shift will take package name 'Student' 
    # and assign it to variable 'class'
    my $class = shift;
       
    my $self = {
                'name'=> shift,
                'age'=> shift,
                'roll_no' => shift
               };
       
    # Bless function to bind object to class
    bless $self, $class;
       
    # returning object from constructor
    return $self;
}
   
# Method for displaying the details
sub get_details
{
    my $self = shift;
      
    print "Name is: $self->{'name'}\n";
    print "Age is: $self->{'age'}\n";
    print "Roll_no is: $self->{'roll_no'}";
}
    
# Object creation and calling
my $obj1 = Student->new("Rahul", 25, 12);
$obj1->get_details();


In the above code, if there is a need to access the data of the class for any modifications or just to print the data of the class then it can not be done directly. There is a need to create an object of that class and then access the data using the get_details() method. This process is termed as Data Encapsulation. Advantages of Encapsulation:

  • Data Hiding: The user will have no idea about the inner implementation of the class. It will not be visible to the user that how the class is stored values in the variables. He only knows that we are passing the values to accessors and variables are getting initialized to that value.
  • Increased Flexibility: We can make the variables of the class as read-only or write-only depending on our requirement. If we wish to make the variables as read-only then we have to only use Get Accessor in the code. If we wish to make the variables as write-only then we have to only use Set Accessor.
  • Reusability: Encapsulation also improves the re-usability and easy to change with new requirements.
  • Testing code is easy: Encapsulated code is easy to test for unit testing.

Encapsulation is one of the fundamental principles of object-oriented programming (OOP), which refers to the practice of hiding the implementation details of an object from the outside world and restricting access to that object’s internal state. This is done to improve code maintainability, reduce coupling between classes, and prevent unintended modification of object state.

In Perl, encapsulation can be achieved through the use of private and public methods and data members. Private methods and data members are not accessible from outside the class, while public methods and data members can be accessed by any code that has access to the object.

Here’s an example of encapsulation in Perl:

Perl




#!/usr/bin/perl
# your code here
#!/usr/bin/perl
 
# Define a class with private and public methods and data members
package Employee;
sub new {
    my ($class, $name, $age, $salary) = @_;
    my $self = {
        name => $name,
        age => $age,
        salary => $salary,
    };
    bless $self, $class;
    return $self;
}
 
# Private method to calculate bonus
sub _calculate_bonus {
    my ($self) = @_;
    return $self->{salary} * 0.1;
}
 
# Public method to print employee details
sub print_details {
    my ($self) = @_;
    print "Name: $self->{name}\n";
    print "Age: $self->{age}\n";
    print "Salary: $self->{salary}\n";
    my $bonus = $self->_calculate_bonus();
    print "Bonus: $bonus\n";
}
 
# Create an object of the class
my $emp = Employee->new("John Doe", 30, 50000);
 
# Call the public method to print employee details
$emp


Output

 

In this example, we define a class Employee with a private method _calculate_bonus and a public method print_details. The new method is used to create an object of the class and initialize its data members. The print_details method prints the employee’s name, age, salary, and bonus, which is calculated using the private method. The _calculate_bonus method is not accessible from outside the class and cannot be called directly.

This example demonstrates how encapsulation can be used to hide the implementation details of an object from the outside world, while still allowing access to its public interface. By doing so, we can improve code maintainability, reduce coupling between classes, and prevent unintended modification of object state.

Advantages of encapsulation in Perl:

  1. Code maintainability: Encapsulation makes it easier to modify and maintain code because the implementation details of an object are hidden from the outside world. Changes to the internal state of an object do not affect the code that uses the object.
  2. Reduced coupling: Encapsulation reduces the coupling between classes, which makes it easier to modify and reuse code. Classes can be modified without affecting the code that uses them.
  3. Code reuse: Encapsulation promotes code reuse because objects can be reused in different contexts without affecting the code that uses them.
  4. Data protection: Encapsulation protects the data of an object from accidental or intentional modification by external code. This prevents bugs and security vulnerabilities.

Disadvantages of encapsulation in Perl:

  1. Overhead: Encapsulation can add overhead to the code, especially if there are many small objects. This can affect the performance of the program.
  2. Complexity: Encapsulation can make code more complex because it introduces additional layers of abstraction. This can make it harder to understand and modify the code.
  3. Maintenance: Encapsulation can make it harder to maintain code because it can be more difficult to trace errors back to their source. This can make debugging more time-consuming and challenging.
  4. Overall, the advantages of encapsulation in Perl outweigh the disadvantages. Encapsulation is a fundamental principle of object-oriented programming that improves code maintainability, reduces coupling between classes, and protects data from unintended modification. While it can add complexity and overhead to the code, these issues can be managed through careful design and testing.


Last Updated : 12 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads