Your skill will accomplish what the force of many cannot |
|
PerlMonks |
Abusing Exporter for Conditional Inheritanceby mojotoad (Monsignor) |
on Mar 17, 2005 at 00:11 UTC ( [id://440207]=perlquestion: print w/replies, xml ) | Need Help?? |
mojotoad has asked for the wisdom of the Perl Monks concerning the following question:
Hello fellow monks,
I've got a situation where I sometimes want my class to inherit from Class A, and somtimes from Class B, depending on user request. Let's say, for example, that my class is a type of StoneGatherer class and that most of the time I just want to gather Blue stones. Every now and then, however, I want to gather Red stones. There is no real difference between how the stones are gathered, just in what type of stones are returned. I do indeed have to inherit from a Gatherer class of some sort -- has_a won't cut it. (and for the curious here, the two Gatherer classes in question are HTML::Parser and HTML::TreeBuilder (which itself isa HTML::Parser)). Obviously I could make two classes, StoneGatherer::Blue and StoneGatherer::Red, which inherit from Gatherer::Blue and Gatherer::Red, respectively. But given that there's no difference in the gathering process, only what is gathered, it seems sort of silly. What I'd like to do is abuse Exporter, overriding import() in such a way that I can just do this:
vs this
Now, it also occurs to me that I'm thinking about the problem completely wrong -- as I'm sure all the OO purists out there are probably screaming right now. For example, this might be a case where a 'mixin' solution is preferred. I'd like to know a) if it is wrong, how wrong is it, b) what's the 'right' way to think about the problem, and c) if there are multiple solutions, what are they?
Thanks for your time and thoughts, P.S. As an aside, there are examples of abusing Exporter out there, such as with Test::More:
Any other examples out there? ;) Update: in tracking down references, I came across the following illustration in the PerlDesignPatterns wiki regarding the AbstractClass pattern: Explicitly using, then adding to @ISA, a marker interface is kind of ugly. One solution is to move part of the work to the abstract marker class:So, at least there's precedent out there for mussing around with @ISA using import().
Back to
Seekers of Perl Wisdom
|
|