hashin_p has asked for the wisdom of the Perl Monks concerning the following question:

I came across this statement in one of the perl references. "Package names should never be hardcoded. You must always use the package name obtained as the first argument to supply to bless. This enables a constructor to be inherited" How does this affect inheritance?

Replies are listed 'Best First'.
Re: Package Name and Inheritance
by erroneousBollock (Curate) on Nov 14, 2007 at 09:57 UTC
    The following is a fairly typical example of a simple constructor for the Stuff class:

    package Stuff; sub new { my $class = shift; my %args = @_; bless { fooAttr => $args{foo}, barAttr => $args{bar}, }, $class; } 1;

    If you bless the attribute hash into 'Stuff' rather than $class, a subclass of Stuff (say Junk) which calls the super-class's constructor will be blessed into the Stuff package instead of the Junk package.

    If Junk adds/overrides any methods, they won't be called.

    Another problem is that it's much harder to maintain a class if the classname is sprayed all over its constituent modules.

    -David

Re: Package Name and Inheritance
by dragonchild (Archbishop) on Nov 14, 2007 at 15:22 UTC
    To further elaborate, the signature for bless is bless( $ref, $class = __PACKAGE__ ). In other words, you have to pass it the reference that you're blessing. If you pass it a classname, it will bless the $ref into that class. If you don't, it will default to __PACKAGE__ which is a built-in that resolves to the current package name. If you inherit the constructor and that constructor uses the single-arg form of bless, you won't ever get an object of your child class.

    My criteria for good software:
    1. Does it work?
    2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?