Is there anything wrong/bad about declaring $self outside the scope of a constructor?
my $self = {}; sub new { my $proto = shift; my $class = ref($proto) || $proto; bless $self, $class; return $self; }
Why did I do this? Because it allows me to access $self in the class's 'private' methods without having to pass it:
sub public_method { my ($self,$args) = @_; $self->{foo} = $args; _do_private_stuff(); } sub _do_private_stuff { print $self->{foo}; }
as opposed to:
sub public_method { my ($self,$args) = @_; $self->{foo} = $args; $self->_do_private_stuff(); } sub _do_private_stuff { my $self = shift; 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)

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:

//avert your eyes - Java code ahead class Ball { private Color color; public Ball(Color c) { this.color = c; } }
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->'?

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.