develooper Front page | perl.perl5.porters | Postings from March 2011

RE: Revising Perl's OO docs - a new OO tutorial

Thread Previous | Thread Next
From:
Jan Dubois
Date:
March 7, 2011 13:46
Subject:
RE: Revising Perl's OO docs - a new OO tutorial
Message ID:
01c701cbdd11$0ba3ae50$22eb0af0$@activestate.com
On Mon, 07 Mar 2011, Ricardo Signes wrote:
> * Chris Prather <chris@prather.org> [2011-03-07T15:21:44]
> > On Sun, Mar 6, 2011 at 9:34 PM, Father Chrysostomos
> > <sprout@cpan.org> wrote:
> > > If we do add object attributes to Perl, it would be very nice if
> > > we could use ‘$obj->attr = $foo’ syntax, instead of $obj-
> > > >attr($foo), which is currently widely used mainly because the
> > > former is so hard to do (that can change, of course).
> >
> > It's my (not-so-humble) opinion this is a horrible idea. It violates
> > encapsulation and confuses the behavior with state in a way that
> > will only lead to *more* confusion down the line.
>
> He didn't say that it would have to be lvalue subs.
>
> Look at how Ruby does this: you provide an "attr=" method that is
> called on assignment, so you are not violating encapsulation or
> confusing behavior with state. It's sugar for a normal method call,
> which can have any behavior you want and mutates whatever state system
> it wants however it wants.

You could also just use hash syntax for your attribute accessors,
and implement your object using a tied hash.  People seem to assume
that exposing attributes as hash elements somehow "leak" your
implementation, but that simply isn't true.  E.g. Win32::OLE
uses this mechanism to expose property accessors to the underlying
COM objects:

    my $Search = $Doc->Content->Find;
    my $Replace = $Search->Replacement;

    $Search->Font->{Bold} = 1;
    $Replace->{Text} = 'B<^&>';
    $Search->Execute({Replace => wdReplaceAll});

None of those "hash element assignments" actually store data into the
object, they call a PROPERTYPUT method via the IDispatch interface
on the COM object instead.

You actually need 2 hashes per object for this though, one for the
externally visible tied interface, and one to store the internal
object data.

Cheers,
-Jan



Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About