jeffa has asked for the wisdom of the Perl Monks concerning the following question:
Why did I do this? Because it allows me to access $self in the class's 'private' methods without having to pass it:my $self = {}; sub new { my $proto = shift; my $class = ref($proto) || $proto; bless $self, $class; return $self; }
as opposed to:sub public_method { my ($self,$args) = @_; $self->{foo} = $args; _do_private_stuff(); } sub _do_private_stuff { print $self->{foo}; }
but since I have _NEVER_ seen this done before, I am led to believe that it is baaaaaad. . . (/me thinks about subclassing)sub public_method { my ($self,$args) = @_; $self->{foo} = $args; $self->_do_private_stuff(); } sub _do_private_stuff { my $self = shift; print $self->{foo}; }
Now that I think about, this is one of those little quirks that has always confused me about Perl's OO: the fact the the class's properties are tucked away in an anonymous data structure (conventionally named self) which is in turn, conveniently tucked away inside a constructor.
Contrast that to Java's OO model where the properties are defined OUTSIDE of the constuctor:
Also, if defining $self outside the constuctory is bad, does anyone know of another way to access $self in 'private' function without having to pass it around, or should I just bit the bullet and define a vi macro for '$self->'?//avert your eyes - Java code ahead class Ball { private Color color; public Ball(Color c) { this.color = c; } }
Thanks,
Jeff
p.s. when I say 'private', please don't think that I am trying to fake private methods in Perl - I am not concerned about that, I am just trying to find new ways to type less :P
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
(crazyinsomniac) Re: OOP Question - location of $self
by crazyinsomniac (Prior) on Apr 16, 2001 at 05:25 UTC | |
by tilly (Archbishop) on Apr 16, 2001 at 07:19 UTC | |
|
Re (tilly) 1: OOP Question - location of $self
by Anonymous Monk on Apr 16, 2001 at 05:29 UTC | |
|
Re: OOP Question - location of $self
by dws (Chancellor) on Apr 16, 2001 at 10:14 UTC | |
by virtualsue (Vicar) on Apr 16, 2001 at 16:45 UTC | |
|
Re: OOP Question - location of $self
by Fastolfe (Vicar) on Apr 16, 2001 at 20:38 UTC | |
by dws (Chancellor) on Apr 16, 2001 at 22:01 UTC | |
by tye (Sage) on Apr 16, 2001 at 22:09 UTC | |
|
(jeffa) Re: OOP Question - location of $self
by jeffa (Bishop) on Apr 16, 2001 at 23:51 UTC |