the presentation of "private" in programming languages

A. Pagaltzis pagaltzis at gmx.de
Thu Mar 15 12:04:06 EDT 2007


* Kragen Javier Sitaker <kragen at pobox.com> [2007-02-26 09:40]:
> The advantage of mandatory information hiding is that this task
> becomes simpler. If I'm changing the semantics of a private
> method in C++, I need only look within that method's class for
> calls to the method; I don't need to look anywhere else.
> 
> I have occasionally wished for this feature in Perl on a
> 100 000-line project.

This is indeed a weakness. In Perl circles, a common slogan is
that Perl prefers that you stay out of someone else’s living room
because it’s the polite thing, not because they’re standing there
with a loaded shotgun. When I first heard this, I eagerly agreed
with it and scoffed at the notion that mandatory controls were
necessary. Just use a convention, they said, that lets people
know which things are private; if they insist on going there
anyway they’ll eventually get what they asked for.

I still agree with the basic stance. It falls broadly in the
scope of “freedom vs. safety” (as Kevin Barnes places it). Stated
in the absolute the way Perl folks like to put it, however, is
naïve. The problem isn’t how to keep away the people that won’t
stay away; it’s how to keep yourself from spilling into all of
your surroundings. F.ex., because it’s not possible to have a
private method in Perl, only private-by-convention methods, the
author of any subclass must be aware of the names of the private
methods in all of its superclasses, so as not to inadvertently
redefine one of them. This is not just a theoretical scenario,
since subclasses are closely related to their superclasses. So
they may well have private methods for related things, which may
then well suggest the same name.

Of course, Perl being Perl, you can actually get semantics out of
it that it doesn’t initially seem to provide, if you work for
them. This is much like getting useful OOP out of the language,
only in this case, the solution is straightforward: use anonymous
functions stored in file-scoped lexicals for private stuff.

    # canonicalises the parameters of public methods
    # based on some object-internal state
    my $check_foo_flag = sub {
        my $self = shift;
        # ...
    };

    sub do_some_public_operation {
        my $self = shift;
        my ( $foo, $bar, $baz ) = $self->$check_foo_flag( @_ );
        # ...
    }

Note that using the `$invocant->$subref()` syntax disables
dynamic lookup – which happens to be exactly what we want for
private methods.

Regards,
-- 
Aristotle Pagaltzis // <http://plasmasturm.org/>


More information about the Kragen-discuss mailing list