Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Brief OO question

by ltp (Beadle)
on Oct 05, 2011 at 01:23 UTC ( #929698=perlquestion: print w/replies, xml ) Need Help??
ltp has asked for the wisdom of the Perl Monks concerning the following question:

Greetings Monks, I did some searching on this question (both internally and using Google) but found nothing definitive. The OO paradigm;
sub method {
    my $self = shift;
Is deeply ingrained in memory of my fingers, however when writing some code for various getter methods, my subconscious predisposition for terseness shortened:
sub get_foo {
    my $self = shift;
    return $self->_bar(baz => 2, frob => 30);
}
To:
sub get_foo { return $_[0]->_bar(baz => 2, frob => 30) }
The question I have is; is using '$_[0]' rather than '$self = shift' considered bad form?

Replies are listed 'Best First'.
Re: Brief OO question
by armstd (Friar) on Oct 05, 2011 at 02:51 UTC

    Not in my opinion, but I rarely do it. My main considerations for doing so are maintainability and performance. If it's a trivial method called often, I'll definitely consider using $_[0] instead of assigning $self first, like your example.

    If it's a method that does considerable or complicated things to "$self", or isn't called very often, then I consider $self more maintainable and will prefer it.

    --Dave

Re: Brief OO question
by chromatic (Archbishop) on Oct 05, 2011 at 16:54 UTC

    You have to weigh the clarity of a named variable versus the efficiency of accessing @_ directly rather than shifting it off. It's a maintenance decision.

    For my purposes, using something like Moose to avoid having to write accessors is worth it.


    Improve your skills with Modern Perl: the free book.

Re: Brief OO question
by Anonymous Monk on Oct 05, 2011 at 06:50 UTC
Re: Brief OO question
by zwon (Abbot) on Oct 05, 2011 at 11:09 UTC

    It is matter of taste. I usually write

    sub get_it { shift->{it} }
      I also use shift like this if it's a one-liner method, nice and short.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://929698]
Approved by ww
help
Chatterbox?
LanX already said this, days ago!

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (10)
As of 2017-05-25 12:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?