Hi! Please consider following me on twitter: @hanekomu.

Use parent.pm instead of base.pm

For years, the common way for your class to inherit from one or more superclasses was the base module. For example:

package Game;
sub new { bless {}, shift }

package Baduk;
use base 'Game';

This works, but some people, me included, aren't quite happy with that. Basically, the above could also be expressed as:

package Game;
sub new { bless {}, shift }

package Baduk;
our @ISA = qw(Game);

If the two packages were in different files, the Baduk package would have to load the file where the Game package lives in as well. But that's about it.

However, base.pm goes further than that. It supports deprecated pseudohases, tries to be clever with $VERSION and generally just does too much. A lot of cruft has accumulated over the years. So a new module, parent, was forked from base.pm and cleaned up.

Using parent.pm is pretty much the same as base.pm:

package Game;
sub new { bless {}, shift }

package Baduk;
use parent 'Game';

This will try to load Game.pm as well. If the Game package is in a different file that is already loaded, you can tell parent.pm not to try to load the file:

package Game;
sub new { bless {}, shift }

package Baduk;
use parent -norequire, 'Game';

Compare the source of the two modules and you will find that parent.pm is a lot cleaner and easier to understand.

Write a comment | Bookmark and Share

posted at: 23:26 | path: /cpan_gems | permalink | 3 comments | 0 trackbacks

Aristotle Pagaltzis wrote at 2010-03-18 08:19:

That’s not what -norequire is for and it’s not how you should use it.

The use case for -norequire is when the Bar package is contained in Foo.pm and a Bar.pm does not even exist. In that case, trying to load Bar.pm would throw an exception, so you have to use -norequire to inherit from it.

But if Bar.pm exists and is already loaded, no harm done, Perl’s `require` will notice. Do not use -norequire as an optimisation. That will just make your code more order-dependent and therefor more fragile.

hanekomu wrote at 2010-03-18 09:47:

Yes, I believe that's what I said, so no contradiction there. :)

Jeremy Leader wrote at 2010-03-18 18:33:

I think the confusion may stem from the phrase "different file". Hanemoku, I suspect you meant Game is in a file not named Game.pm (i.e. in a "different" file, whether it's in the same file as Baduk, or somewhere else). Aristotle probably interpreted "different file" as meaning "different from the file Baduk is in, possibly named Game.pm". I made the same mis-interpretation; it took me a minute or two after I read your comment to figure out how what you said could be consistent with Aristotle's description of the -norequire use case.

Comments are closed for this story.

Trackbacks are closed for this story.