Ovid has asked for the wisdom of the Perl Monks concerning the following question:
I'm working on a large project with heavy refactoring. Sometimes I am finding myself in the awkward position of refactoring classes in such a way that when I pass objects in argument lists, I am not interested in the class type, but in the class capabilities (similar to Ruby's "duck typing"). In short, I want this:
sub foo { my ($self, $object_or_class) = @_; die $message unless does($object_or_class, @methods); ... }
This is becoming more of a problem as I find a large class which needs to be factored into two or more classes. The does() function is trivial to write (as long as one appreciates the caveats involved), but I was looking to see if there is something on the CPAN which already handles this. I see nothing, but if someone else does, I'd like to hear about it.
First pass of the does() function:
use Scalar::Util qw/blessed/; sub does { my ($proto, @methods) = @_; return if ref $proto && ! blessed $proto; my @coderefs; foreach my $method (@methods) { push @coderefs, $proto->can($method) || (); } return wantarray ? @coderefs : \@coderefs; }
Cheers,
Ovid
New address of my CGI Course.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Class capabilities
by diotalevi (Canon) on Oct 11, 2005 at 21:19 UTC | |
|
Re: Class capabilities
by moot (Chaplain) on Oct 11, 2005 at 21:10 UTC | |
by Ovid (Cardinal) on Oct 11, 2005 at 21:20 UTC | |
by Aristotle (Chancellor) on Oct 11, 2005 at 23:16 UTC | |
|
Re: Class capabilities
by Zaxo (Archbishop) on Oct 11, 2005 at 23:03 UTC | |
|
Re: Class capabilities
by dragonchild (Archbishop) on Oct 12, 2005 at 02:01 UTC | |
by Ovid (Cardinal) on Oct 12, 2005 at 06:11 UTC | |
by dragonchild (Archbishop) on Oct 12, 2005 at 12:57 UTC | |
|
Re: Class capabilities
by adrianh (Chancellor) on Oct 12, 2005 at 09:03 UTC | |
|
Re: Class capabilities
by sgifford (Prior) on Oct 12, 2005 at 15:44 UTC | |
by Ovid (Cardinal) on Oct 12, 2005 at 17:28 UTC |