|go ahead... be a heretic|
Abstract Methods in Mooseby crashtest (Curate)
|on Dec 11, 2009 at 18:57 UTC||Need Help??|
crashtest has asked for the
wisdom of the Perl Monks concerning the following question:
Greetings, wise monks!
After about a year's hiatus, I've recently found an excuse to return to Perl, and decided to finally take Moose out for a spin. After years of using AUTOLOAD to generate accessors/mutators, I feel like I've been (poorly) reinventing wheels when better alternatives were right there on CPAN. Well, no matter...
Probably because I've spent too much time programming in Java, I get this urge to declare abstract methods. I realize the benefit isn't there when using Perl as opposed to a statically typed/compiled OO language such as Java, but I like to clearly point out methods I expect subclasses to implement. So right now, I've written something like:
Now if I forget to implement get_widget_type in my SnazzyWidget class, I get a helpful error message with a stack trace instead of the rather cryptic and confusing "Can't locate object method "get_widget_type" via package "SnazzyWidget"".
I half expected to find a Moose extension that would allow me to express this more concisely, providing a method like
I've done some searching on both PerlMonks and CPAN to no avail. Is my interest in abstract methods misplaced? Or is there some other pattern Moose'ers employ that has a similar effect? Any input you have for me is much appreciated!
I had a suspicion that Moose Roles might lead me to a satisfactory solution, but apparently others have had the same idea... and the manual is quite clear about this:
If you are familiar with the concept of abstract base classes in other languages, you may be tempted to use roles in the same way.
You can define an "interface-only" role, one that contains just a list of required methods.
However, any class which consumes this role must implement all of the required methods, either directly or through inheritance from a parent. You cannot delay the method requirement check so that they can be implemented by future subclasses.