July 25th, 2011
| | Posted in CPAN, Perl
This week, I’m writing from the relative comfort of my hotel room in Portland, as I am attending the 2011 O’Reilly’s Open Source Convention. I always enjoy the hell out of this conference, as it’s great to see people in person that I only correspond with via email the rest of the year. And the caliber of the tech talks seems to go up and up each year.
For this week’s PMM, I’ve chosen a pragma: namespace::autoclean*. This pragma solves a problem that I’m embarrassed to admit I didn’t even know existed— the problem of those functions you import being left laying around in your namespace.
See, the reason I’m embarrassed is that it’s actually quite obvious: when you import a symbol into your namespace, it’s there until/unless you get rid of it. Maybe in some cases you want this to happen, but what about when you’re writing a class? You don’t import methods from other classes, you inherit them. So nothing that you imported is necessary for the user-facing interface your class provides. And if you leave things laying around, your users can call them as methods, though the result might be a mess. Worse, is when the result isn’t a mess, but is something you didn’t want them to be able to do, such as calling
has as a method on your Moose-based class, and thus adding to the class attributes at run-time. You probably don’t want that to happen. Indeed, that is how I came to hear about this module; during RJBS‘s Moose tutorial today, he stressed the importance of ending your Moose-based class with “
no Moose;“, but then as an aside mentioned that he preferred to use namespace::autoclean.
That sort of clean-up is where namespace::autoclean steps in. At the end of a lexical scope, it cleans up everything you’ve imported. Where you used these symbols, they’re still properly bound. But to the outside world (read: clueless and/or nosy users) it’s as if those symbols were never there. And it has options as well, letting you specify additional symbols to clean: have some helper functions that you used, but don’t want users who’ve read your code to call them directly? You can tell namespace::autoclean to take those out of the picture, as well.
It’s a simple module, with a simple purpose. And it solves a non-simple problem. So this week, I recommend giving namespace::autoclean a good look.
* Starting with this week’s PMM, I am linking modules to MetaCPAN.org. I’m really impressed with the new search interface, and the ability to link it to my PAUSE ID, to my GitHub account, PerlMonks, etc. I think it is showing a lot of potential.