Solving the Data Inheritance Problem


You want to inherit from an existing class, augmenting it with a few extra methods, but you don’t know which data fields your parent class is using. How can you safely carve out your own namespace in the object hash without trampling on any ancestors?


Prepend each of your fieldnames with your own class name and a distinctive separator, such as an underscore or two.


An irksome problem lurks within the normal Perl OO strategy. The exact class representation must be known, violating the veil of abstraction. The subclass has to get unnaturally chummy with all its parent classes, recursively.

We’ll pretend we’re a big happy object-oriented family and that everyone always uses hashes for objects, thus dodging the problem of a class choosing an array representation but inheriting from one that instead uses a hash model. (The solution to that problem is aggregation and delegation, as shown in perlbot (1).) Even with this assumption, an inherited class can’t safely use a key in the hash. Even if we agree to use only method calls to access attributes we don’t ourselves set, how do we know that we aren’t setting a key that a parent class is using? Imagine wanting to use a count field, but unbeknownst to you, your great-great-grandparent class is using the same thing. Using _count to indicate nominal privacy won’t help, since gramps might try the same trick.

One reasonable approach is to prefix your own data members with your package ...

Get Perl Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.