Sunday, March 28, 2010

DynaLoader considered harmfulharmful

(This entry was first posted here)

DynaLoader is a portable high-level interface around you OS's dynamic library loading. It's the code that's loading your XS modules. It's actually doing a pretty good job at that. You may wonder then why I consider its use harmful.

If all you want to do is load the XS part of your module, it's the wrong tool for the job. Most of all because it has a truly awful interface. It requires you to inherit your module from it. It's common knowledge that public inheritance from an implementation detail is a really bad idea. It breaks not only encapsulation rather badly, but also violates separation of concerns.

This would be as bad as it is if DynaLoader didn't use AutoLoader. Because of this, when you call some undefined method on an instance of a class that derives from DynaLoader you don't get this error:

Can't locate object method "undefined_method" via package "Foo"

But this rather cryptic error:

Can't locate auto/Foo/undefined_m.al in @INC (@INC contains: /etc/perl /usr/local/lib/perl/5.10.0 /usr/local/share/perl/5.10.0 /usr/lib/perl5 /usr/share/perl5 /usr/lib/perl/5.10 /usr/share/perl/5.10 /usr/local/lib/site_perl .)

No way a perl novice will understand what's going on there!

Worst part may be that this interface buys us very little in practice. The inheritance is used only once in the DynaLoader code, to call the dl_load_flags function. Surely there has to be a better way to pass on that one bit of data!

One solution to this is to simply encapsulate the module loading to a different module. This is a working approach, but then you're reimplementing a module that has been in the perl core for a decade now: XSLoader. It's not perfect, but it will cover 98% of all XS user's needs with significantly less disadvantages.

Honestly, there are valid uses of DynaLoader, but standard XS modules just aren't one of them. Use XSLoader or if that doesn't suit you write a patch for it or a better wrapper and put it on CPAN*, but don't use DynaLoader directly.

* I might even do that myself.