Information Hiding In Perl

A response to EncapsulationDefinition
Not to be nit-picky, but the PerlLanguage does allow for pretty strict information hiding. You just have to work at it more than the easiest way of doing OO in Perl, because whenever there is a choice in Perl, the default is to be open.

If you need full data-hiding (short of using the B modules for picking through Perl's data structures at a *very* low level) you can do something akin to the following:
  ###### SubClassWithPrivateData.pm 
  use base qw(ParentClass);

{ my $privateData;

sub getPrivateData { return $privateData; }

sub setPrivateData { my $new = shift; return $privateData = $new; } }

Note the use of the anonymous scope for the private class data. There are similar tricks in Perl for getting private object data as well.

Inheritance in such an object schema can be tricky, because you have now successfully really hidden the $privateData variable. Even the subclass can't see it directly, so if you implement getPrivateData in a subclass, you must call the superclass method to actually access the variable. Inside that anonymous scope, lexically speaking (textually, in other words) is the only place where the variable $privateData is in scope.

-- JeffBay You can do anything in Perl! (ThereIsNothingPerlCannotDo!)


Then again, you should reconsider whether you really, really need to do information hiding (in Perl).


It definitely goes against the grain in Perl. The idea in Perl is that you should be able to tell your users what your living room consists of, and please don't leave a coffee stain on the desk. If they have a reason to walk all over the living room, they are expected to wipe their feet first, and don't assume the couch is in the same place it was last time they visited.

I just wanted to point out that you could do it in Perl. I'd like to do it in Java, but nobody will pay me to do Java, everybody wants me to do Perl because that is what I've done in the past.

-- JeffBay


Or to quote from LarryWall & TomChristiansen in the CamelBook:

"The trend over the last 20 years or so has been to design computer languages that enforce a state of paranoia. You're expected to program every module as if it were in a state of siege. Certainly there are some feudal cultures where this is appropriate, but not all cultures are like this. In Perl culture, by contrast, you're expected to stay out of someone's home because you weren't invited in, not because there are bars on the windows."

But Larry also said: "In general, if you think something isn't in Perl, try it out, because it usually is. :-)"


Looks pretty complicated to do something so common for an "object oriented" language. And it is. The idea is that you don't need to do it in almost all cases.


CategoryInformation CategoryPerl

EditText of this page (last edited October 22, 2003) or FindPage with title or text search