开发者

Is using __PACKAGE__ inside my methods bad for inheritance?

If inside my code I'll have calls like:

__PACKAGE__->method;

will this li开发者_如何学运维mit the usability of this module, if this module is inherited?


It depends on what you want to do:

#!/usr/bin/perl

package A;

use strict; use warnings;

sub new { bless {} => $_[0] }

sub method1 {
    printf "Hello from: %s\n", __PACKAGE__;
}

sub method2 {
    my $self = shift;
    printf "Hello from: %s\n", ref($self);
}

package B;

use strict; use warnings;
use parent 'A';

package main;

my $b = B->new;

$b->method1;
$b->method2;

Output:

Hello from: A
Hello from: B


If you intend to inherit that method, call it on the referent and don't rely on the package you find it in. If you intend to call a method internal to the package that no other package should be able to see, then it might be okay. There's a fuller explanation in Intermediate Perl, and probably in perlboot (which is an extract of the book).

In general, I try not to ever use __PACKAGE__ unless I'm writing a modulino.

Why are you trying to use __PACKAGE__?


That depends. Sometimes __PACKAGE__->method() is exactly what you need.

Otherwise it's better to use ref($self)->class_method() or $self->method().


"It depends." is the correct answer. It is relatively uncommon to actually need the package name; usually you will have an instance or a class name to start with. That said, there are times when you really do need the package name -- __PACKAGE__ is clearly the tool for that job, being superior to a literal. Here are some guidelines:

Never call methods off __PACKAGE__ inside methods, as doing so makes it impossible for inheritors to change your implementation by simply overriding the called method. Use $self or $class instead.

Try to avoid __PACKAGE__ inside methods in general. Every use of __PACKAGE__ adds a little bit of inflexibility. Sometimes, inflexibility is what you want (because you need compile-time resolution or badly want to control where information is being stored), but be triply sure that what you want is worth the cost. You'll thank yourself later.

Outside of methods, you don't have access to a $self, and should call methods off __PACKAGE__ rather than a literal. This is mostly important for compile-time declarations like those provided by Class::Accessor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜