March 2010 Archives

Separation of Concerns

In the world of Perl programming, nothing annoys me more than opening up a module and finding a bunch of POD interleaved with code. I've heard people argue in favor of this atrocious practice, saying that it allows the documentation for a function to be next to its implementation. But if I'm reading the code at all, it's only because I've already read the documentation and it wasn't good enough. That's not meant to be an insult -- maybe I was trying something weird that the author didn't intend, or trying to track down a bug that the author was not aware of.

The purpose of documentation is to describe the public interface of your module. Ideally, your module is perfect, and nobody should ever have to look under the hood, because all anyone could ever need is the publicly provided interface. But of course, no module is perfect; there are bugs, there are desired features that aren't there. There are functions that work fine but execute in exponential time under one circumstance that nobody thought of.

If someone's looking at your code, it's because they need more information than the documentation or interface itself can provide. Interrupting the flow of code with chunks of POD makes it that much harder to follow what's going on. If you're looking at your own code, you almost certainly don't need the POD there in front of you, but if you do, maybe your interface is too complicated.

Also, does anyone know of an Emacs thingy that will hide POD upon the mashing of a magical sequence of keys?


I need closure

Suppose you wanted to create a list of closures, each of which spits out a new number in sequence. Pretty easy:

my @subs;
foreach my $num( 1 .. 10 ) { 
    push @subs, sub { return $num };

print $_->(), "\n" for @subs;

This is a simplified example of something I needed to do in Javascript, but I did it wrong.

About Mike Friedman

user-pic Mike Friedman is a professional computer programmer living and working in the New York City area.