Code Reuse

October 4, 2009

At work, I have been refactoring old Perl code. Part of me feels that this was tangential to the main aims of the project I've been assigned, but another part of me can list all the bugs I've found/fixed and the advantages in terms of maintainability, so on balance I think it was a good idea.

Something I like even more than tidying code is reducing the amount of code required. (I've been doing a lot of that as well.) Breaking code into reusable modules is the essence of what I'm trying to achieve - later projects within the company (and perhaps beyond) should not have to reinvent what I'm writing. I'm attempting to replace boilerplate code with existing modules from CPAN where I can - I'm fortunate in that this seems to be possible licensing-wise within our product.

Now, there is some code which loops over a list of plugins, and forks off a background process to deal with each of them. Which CPAN module should I use? There are a few which look promising (like the classic Proc::Daemon), but force the parent process to exit. Not good for a loop. There's one which does dodgy hacks with parsing the output of 'ps', rather than using 'kill 0 => $pid' like every other module. Some handle pidfiles (which I want, provided I can customize the name, but what if I didn't?), and some don't (which is fine, I'll just use one of the separate pidfile modules). But why do CPAN modules reimplement the pidfile handling themselves anyway?

One of the best approaches I've seen so far is MooseX::Daemonize. Moose's role system looks like it would be very useful, but I'm a bit hesitant to introduce Moose to the company just yet. Maybe I should.

My point is, there is all this code, but subtle problems are preventing its reuse. I see the same thing going on at work; there are some utility libraries, but they contain large numbers of mostly unrelated functions. Developers often do not spot code which might be useful later, so they are left as a subroutine in a script. Ironically, I am reimplementing these functions in a more modular fashion, and hopefully this will catch on.

Nifty tech tag lists fromĀ Wouter Beeftink