Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I establish inheritance at compile-time rather than runtime, and if so why?

AFAIK inheritance in Perl is usually set up like this:

package Mule;
our @ISA = ("Horse", "Donkey");

Are there any examples where use base (or use parent) is better instead?

like image 895
Eugene Yarmash Avatar asked Feb 13 '10 11:02

Eugene Yarmash


2 Answers

use base qw(Horse Donkey);

This is roughly equivalent to:

BEGIN {
    require Horse;
    require Donkey;
    push @ISA, qw(Horse Donkey);
}

It is tidier if you need to load the modules code as well as inheriting from them. BTW, there are issues with multiple inheritance, but thats a different question :)

Edit: Compile-time v. run-time advantages:

  • You have the safety of the compile-time check with use base meaning your script won't even start if your base module is not present on the filesystem.
  • If you want to decide to use a given module at run-time, then you can test and add the module to your parents:

    if (eval { require X }) { push @ISA, 'X'; }

like image 196
ziya Avatar answered Sep 19 '22 00:09

ziya


Establishing inheritance at compile time avoids a particularly hard to debug dependency loop, illustrated below.

# Child.pm
package Child;

our @ISA = qw(Mother);

use Foo;

# Mother.pm
package Mother;

sub wibble { 42 }

# Foo.pm
package Foo;

use Child;
Child->wibble;

If you "use Child" before "use Foo" then Foo will try to call Child->wibble before its established its inheritance on Mother. If instead Child were to use parent qw(Mother) its inheritance would be established before it tried to load anything else.

I've been this sort of dependency loop in private, corporate code that tends to be a bit more intertwined than public code. It sucks to debug, which is why I'd recommend always establishing inheritance at compile-time.

like image 25
Schwern Avatar answered Sep 20 '22 00:09

Schwern