Monkey-patching, subclassing, and accidental overriding

One of the great things about open-source software is the ability to reuse handy classes written by other people. But sometimes, you find yourself using a class that doesn’t have quite enough features for what you’re trying to do. What’s the best way to deal with that sort of situation?

One option would be to monkey-patch new code into the class you’re using — just add extra subroutines to the original namespace. But unconstrained monkey-patching has consequences that make it extremely hard to use in practice. So the usual alternative recommendation is to subclass the upstream code, add the new methods in the subclass, and then ensure that the rest of your program always uses the subclass in place of the original. But that approach has two flaws. First, it can be awkward to make sure your subclass is always used in the right places. Second, it doesn’t actually fix the problem: you can still experience all the same issues as with monkey-patching!

I gave a talk on this topic at this year’s YAPC::EU in Rīga, and it’s getting a repeat (and extended!) outing at the inaugural Dynamic Languages Conference tomorrow. But if you’d like to read the full details, the corresponding paper is now on this website.