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
In reply to OOP Question - location of $self by jeffa
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |