InsideOut objects using tied hashes

Ovid publiustemp-londonpm at
Wed Feb 15 16:22:06 GMT 2006

--- Robert Rothenberg <robrwo at> wrote:

> I've hacked together a distribution for implementing inside out
> objects using tied hashes:
> One then uses the syntax for "traditional" Perl objects:
>   sub method {
>     my $self = shift;
>     return $self->{Field};
>   }
> The downside is that your don't really get encapsulation, since the
> hashes are "our" variables and child classes can sill access fields.
> Which negates the benefits of inside-out classes.

You may be aware of this, but for those who aren't: encapsulation isn't
about keeping folks from seeing inside of your object.  Encapsulation
is about limiting reliance on the internal structure of an object.  So
let's say I have a "name" method:

  sub name {
    my $self = shift;
    return $self->{name} unless @_;
    $self->{name} = shift;

Later on, some other code does this:

  sub foo { return scalar reverse shift->{name} }

That's bad and doesn't scale up for larger systems.  Instead:

  sub foo { return scalar reverse shift->name }

*That's* proper encapsulation.  Why?  Several reasons.  First, your
"name" method can look like this:

  sub name {
    my $self = shift;
    return $self->[NAME] unless @_;
    $self->[NAME] = shift;

In short, you, the author, now have the freedom to alter the internals
of your class without worrying about breaking things.  But what if you
don't alter the internals?  shift->{name} is OK, right?

Nope.  "name" might get calculated or fetched from a data store. 
"name" might be overridden in a subclass.  You might decide that the
key should be changed from "name" to "__name" or something like that.

The encapsulation afforded by limiting one's reliance on a particular
implementation is the greatest stregth of inside-out objects, not
keeping folks from seeing us in our underwear.  Classes should
generally (not always) be written in such a way so as to restrict
implementation reliance to the smallest set of code that one can. 
There are reasons to violate this, but this should be done consciously,
not out of habit.


If this message is a response to a question on a mailing list, please send follow up questions to the list.

Web Programming with Perl --

More information about the mailing list