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"".package AbstractWidget; use Moose; use Carp; sub get_widget_type{ confess(qq["get_widget_type" must be implemented by a subclass!]); }
I half expected to find a Moose extension that would allow me to express this more concisely, providing a method like
orhas_abstract 'get_widget_type'
expects 'get_widget_type'
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.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Abstract Methods in Moose
by stvn (Monsignor) on Dec 11, 2009 at 22:31 UTC | |
by crashtest (Curate) on Dec 12, 2009 at 21:06 UTC | |
by stvn (Monsignor) on Dec 13, 2009 at 00:38 UTC | |
by stvn (Monsignor) on Dec 20, 2009 at 13:33 UTC | |
Re: Abstract Methods in Moose
by brap (Pilgrim) on Dec 11, 2009 at 19:45 UTC | |
by crashtest (Curate) on Dec 11, 2009 at 20:17 UTC | |
by ikegami (Patriarch) on Dec 12, 2009 at 21:56 UTC | |
by Anonymous Monk on Dec 11, 2009 at 21:10 UTC | |
Re: Abstract Methods in Moose
by chromatic (Archbishop) on Dec 12, 2009 at 18:44 UTC | |
by crashtest (Curate) on Dec 12, 2009 at 21:17 UTC |