Meditation, The Art of Exploitation

Thinking? At last I have discovered it--thought; this alone is inseparable from me. I am, I exist--that is certain. But for how long? For as long as I am thinking. For it could be, that were I totally to cease from thinking, I should totally cease to exist....I am, then, in the strict sense only a thing that thinks.

Thursday, February 22, 2007

Perl: a practical OO design of complex system

In this entry, I'll focus on code reuse design by understanding how Exporter works in a complex perl hierarchical software system. The main process daemonizes itself, then it checks its configuration file. For each item listed in the configuration file, it creates a perl object and then daemonizes it.

Entry:
Daemonize
Read config file
For each config item:
+fork-----child process---daemonize
|
+fork-----child process---daemonize
....

Each config item daemonizes and shares some common code such as new, run (main daemon loop method), etc. In C++, this is mostly likely accomplished like this:

template
class base{
public:
base(){}
run(T t){}
};

class HTTP: base{
public:
prep_http_header(){}
};

Here we use the CRTP (curious recursive template pattern) to build the hierarchy inherit base class methods run and constructor in derived class such as a HTTP protocol handler.

With perl, things are a little different:

package network::Base;
use base qw(Exporter);
our @EXPORT_OK = qw(new run);
sub new{}
sub run{}
1;

package network::HTTP;
use network::Base qw(new run);
1;

By declaring the base class an Exporter, Base module can export symbols to classes that use it. As one may soon realize, OO is quite an interesting design in perl. The language itself is very extensible and by simply exporting/importing symbols, it achieves inheritance through the 'use base' and 'Exporter' module. In fact there is nothing special about Exporter module. All that it does is injecting symbols into packages using it. Because 'Perl automatically calls the import method when processing a use statement for a module.', by declaring a Base module inheriting from Exporter, it also inherits the import method and subsequently all modules using Base module will be able to selectively choose symbols to import from Base.