The following little idea seems so simple that I'm surprised that I haven't seen this before.
The following snippet may not work as you expect:
use Test::More tests => 3; + + use_ok('CGI') or die; can_ok('CGI', 'start_html'); ok(CGI->start_html, '... and calling it should succeed');
Running that produces the following output:
1..3
ok 1 - use CGI;
not ok 2 - CGI->can('start_html')
# Failed test (test.pl at line 4)
# CGI->can('start_html') failed
ok 3 - ... and calling it should succeed
# Looks like you failed 1 tests of 3.
What gives? The test says that CGI.pm does not have a start_html() method, but calling that method succeeds. AUTOLOAD() can cause strange behaviors.
Or what about trying to validate the interface of delegated object methods? Just because I can stick any 'ol object in a slot doesn't mean that that object has the methods that I want, but if methods are AUTOLOADed, I can't easily validate them (I was also thinking about this in reference to traits validating required methods, but I don't know how best to implement that yet).
The solution that occurred to me was to provide stub methods:
package Foo; use stub qw'this that'; sub AUTOLOAD {...} # required
Then, when another object needs to validate the interface:
sub _delegate { # this is not a complete method. It's just here for illustratio +n my ($self, $slot, $object) { $self->{$slot}{object} = $object; my @missing; foreach my $method (@{$self->{$slot}{methods}}) { push @missing => $method unless UNIVERSAL::can($object, $met +hod); } die "Interface required @missing" if @missing; return $self; }
Now we can validate the interface even if the methods don't exist.
The actual stub package:
package stub; + + sub import { my @stub_methods = @_; my ($package) = caller; foreach my $stub (@stub_methods) { *{"$package::$stub"} = sub { goto &AUTOLOAD }; } } + + 1;
The package using stubs would be expected to have an AUTOLOAD method capable of handling all of the stub methods.
Did I miss anything? Is this even worth the trouble?
Cheers,
Ovid
New address of my CGI Course.
In reply to Creating stub methods by Ovid
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |