Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good practice in Perl when instance methods call each other over a "$self" reference?

Tags:

oop

perl

Should instance methods in Perl call each other like this:

package BlaBla;

sub foo {
    my($self) = @_;
    #do something awesome;
}

sub bar {
    my($self) = @_;
    foo();
}

Or like this:

package BlaBla;

sub foo {
    my($self) = @_;
    #do something awesome
}

sub bar {
    my($self) = @_;
    $self->foo();
}

Thank you all for your time.

like image 868
AlexTheBird Avatar asked Jun 29 '11 13:06

AlexTheBird


2 Answers

Yes, you should include $self - if you don't, polymorphism won't work because each method will look for all calls in its own package, even if they're overridden in a subclass. Worse, if the referenced method is inherited from a parent and not overridden in the current subclass, the program will die because it doesn't exist in that package. And that's even if you do remember to try to fake out Perl's OO mechanism by passing $self as the first parameter.

like image 90
Dave Sherohman Avatar answered Oct 04 '22 20:10

Dave Sherohman


If foo() is a method that can be called from other places you should certainly always call it as a method, otherwise classes inheriting from you won't be able to override it, and you'll force your foo() to check if it's being called in a methody-way or in a functiony-way.

On the other hand, if foo() is just some helper code that a few of your methods use, and is quite specific to your implementation of the class, then you can call it directly, but should then really always call it directly, and might want to label it as a private function available to the class by prefixing its name with an underscore: _foo().

like image 30
Alex Avatar answered Oct 04 '22 22:10

Alex