Subclassing Perl Interfaces

Gerry Gleason, who has done a ton of work for PurpleWiki recently, and I have had an ongoing discussion about when to use base classes in Perl. The reason the question comes up at all is that Perl base classes do not behave the way base classes do in “real” object-oriented languages. Because Perl does very little in the way of type-checking, defining interfaces as Perl base classes doesn’t give you the same benefits as it would in other languages.    (4PS)

Nevertheless, when you have multiple classes with the same interface, I think it’s good practice to define the interface in a base class, if only for the discipline of doing so. When we were designing a new pluggable back-end architecture for PurpleWiki, Gerry and I first discussed the API using the Wiki, then Gerry went off and implemented three different backends simultaneously. Today, I created a base class for those backends, and in the process of subclassing them, I discovered a bunch of inconsistencies and subtle bugs in the implementation. The point is not that Gerry is a sloppy programmer. Anyone would have made the same mistakes in the process of implementing a new architecture quickly, especially doing (and learning from) multiple implementations simultaneously. The point is that the process of creating a base class forced us to rigorously examine the interfaces of each implementation. Even though Perl doesn’t do as much as it could with base classes, the processing of implementing base classes and subclassing them forces us to do our own checking, which results in better code.    (4PT)

Perl doesn’t leave you totally helpless when it comes to base classes, although again, you have to do extra work to get the behavior you want. For example, you can “assure” that methods are overloaded by defining methods that croak in the base class. If these methods are not overloaded, then they will croak when they are called.    (4PU)

Leave a Reply