Back

"use base" and "use parent"

Object oriented programming has become much easier with the recent versions of Perl. One of the strangest things in the "old" days of PerlOO was the @ISA array. This array listed the modules of which a module inherits its functions. However, in order to make really use of an inherited function, one had to load the related package as well. All this looked a bit clumsy and used to confused people who started programming Perl. As I said, things have changed: now there are the base and parent modules coming with Perl's core.

Today, use base is often seen in newer Perl modules, because it makes the code in a module's headers much easier to read. It does quite a good job when it comes to writing a class that is based only on one super-class (and that class is also based only on one super-class, and so on). With other settings this module seems to have problems. This is important to note, because the documentation ("perldoc base") provides an example of multiple inheritance but later states that multiple inheritance is actually not supported.

Well, this is only half of the truth. It appears that multiple inheritance using use base appears to be OK as long as both classes are simple base classes. It starts to break and causes strange errors in cases in which the super classes are further up in the dependency tree and also make use of multiple inheritance. The stupid thing is that the documentation states that in case of problems error messages will be thrown, however, this was not the case when I used base classes that inherited functions from multiple base classes, of which one was Class::Accessor, a class that does automatic code generation.

This is where the less famous "parent" module comes into the game. The documentation (perldoc parent) states that "this module was forked from base to remove the cruft that had accumulated in it". This usually means the code is more modern than the original code. And in fact, use parent allows one to have super classes that use themselves multiple inheritance.

The documentation is not too obvious with this regard and it needs more testing to prove the behaviour of use base and use parent.

For now the rule of thumb for choosing on of these modules for object oriented Perl is as following.

  • use base is good if used with actual base classes.
  • use parent is good if the super classes are not base classes
  • use parent is good if one needs multiple inheritance