Auto-wrapping subclass methods Geeky CMU memories
Jun 01

Last month I described custom code for wrapping certain methods of CHI driver subclasses, regardless of how far down the class hierarchy they were. I said I felt like I must be reinventing the wheel, and sure enough, Tim Bunce gently pointed me at Moose’s application of roles to instances.

When I first heard about this feature I instinctively dismissed it because it sounded inefficient, as if each instance were individually marked with a list of roles. In fact, the implementation is perfectly efficient. When you apply a role to an instance, Moose simply applies the role to the instance’s class to create a new anonymous class, then reblesses the instance into it. This is cached, so the next time you apply the same role to the same kind of object, the cached class can be used.

Now I’ve eliminated my custom code and have several roles working in CHI, each of which is activated by certain constructor parameters:

  • IsSizeAware – activated if is_size_aware or max_size is specified
  • HasSubcaches – activated if l1_cache or mirror_cache is specified
  • IsSubcache – activated for subcaches themselves

Moving these features out into separate roles has cleaned up the main driver code considerably. It also speeds up the common case, since we don’t have to check for these things on each call.

This does mean that CHI now depends irrevocably on Moose. For a short time we tried to compromise with Mouse as a way to minimize dependencies and application startup cost, but the role support just isn’t there, and even the authors of Mouse are now publicly discouraging its use. Given the intelligence and drive of those working on Moose, I feel confident that it will continue to get faster and make its way into ever more Perl installations.

Leave a Reply

preload preload preload