Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data Encapsulation in Perl?

Hello Perl community on SO. I am using Perl since a few years, but since I am following SO, I recognized that I know Perl not enough.

I wrote I quite big script over the past 4 years and tried to do this in OO style. I know that Perl<6 is not really OO.

So one point I don't like is that I have no data encapsulation, that means no Variables that are really private to a package ("class") (or maybe I don't know how to do it).

I have something like this (only a small part of my script)

package TAG;

sub new () {
    my $classname = shift;
    my $self      = {};

    bless( $self, $classname );
    $self->initialize();
    return $self;
}

sub initialize() {
    my $self = shift;

    # Only an example, I have a long list of items in this "class"
    $self->{ID}          = "NA"; 
}

sub setID() {
    ...
}

sub getID() {
    ...
}

In my main script I am using it then this way:

my $CurrentItem;
$CurrentItem = new TAG();

$CurrentItem->getID()

but

$CurrentItem->{ID} = "Something";

is also working, but I would prefer, that this is not possible.

Is there a way to get a better encapsulation of the data I am using in the "class", so that I am (or other users are) forced to use the get and set methods?

like image 638
stema Avatar asked Mar 24 '11 13:03

stema


People also ask

What is data encapsulation with example?

Data Encapsulation is an Object Oriented Programming concept that bind a group of related properties, functions, and other members are treated as a single unit. Class is the best example of Data Encapsulation. It sometimes referred to as data hiding that prevents the user to access the implementation details.

What is encapsulation of data?

Data encapsulation, also known as data hiding, is the mechanism whereby the implementation details of a class are kept hidden from the user.

Does Perl have OOP?

Summary: in this tutorial, you will learn about Perl Object-Oriented Programming or Perl OOP. You will learn how to create a simple Perl class and use it in other programs. Besides procedural programming, Perl also provides you with object-orient programming paradigm.


1 Answers

This is an issue that's been discussed in several places, and there are several possible work-arounds, but none of them are necessarily ideal.

This paper discusses options such as closures, scalars, and a limited access hash using Tie::SecureHash, preferring the last approach.

This blog argues that in perl there are times when encapsulation should be violated, although the comments bring up some negatives for doing so.

You can also look into moose for your Perl 5 objects. It's written to encourage the use of encapsulated objects.

like image 77
justkt Avatar answered Oct 11 '22 12:10

justkt