Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re^4: A working strategy to handle AUTOLOAD, can(), and (multiple) inheritance without touching UNIVERSAL?

by lodin (Hermit)
on Aug 31, 2009 at 21:49 UTC ( [id://792476]=note: print w/replies, xml ) Need Help??


in reply to Re^3: A working strategy to handle AUTOLOAD, can(), and (multiple) inheritance without touching UNIVERSAL?
in thread A working strategy to handle AUTOLOAD, can(), and (multiple) inheritance without touching UNIVERSAL?

As the thread here on PM and the two CPAN modules (written by notable Perl people) suggests, this is not as easy as it looks. I think the best way to get it right each time is to find an approach that always acts as "expected", and then put it in a module. I trust a module to be more consistent than me when faced with a repeated problem. :-)

Regarding your suggestions; it fails to behave like I would expect when it is inherited (and upon object destruction, but to be fair you do not have a constructor).

{ package Foo; sub can { my $self = shift; my $method = shift; return sub { print __PACKAGE__ . ": autoloaded $method\n" }; } sub AUTOLOAD { my $code = $_[0]->can(our($AUTOLOAD) =~ /.*::(.*)/s); goto &$code; } } { package Bar; our @ISA = Foo::; sub new { bless {} => shift } sub bar { print __PACKAGE__ . ": bar\n" } } my $o = Bar::->new; my $m = $o->can('bar'); $o->$m; $o->bar; __END__ Foo: autoloaded bar Bar: bar Foo: autoloaded DESTROY
In my solution outlined in the root node I handle it by moving the logic that generates the autoloaded subroutine reference to a common routine that both AUTOLOAD and can use. Then I see if UNIVERSAL::can returns anything. If it does it means that AUTOLOAD will not be invoked for $o->bar, so the return value of UNIVERSAL::can should be used instead. (This of course assumes that UNIVERSAL::can is not overloaded to do something else.)

The remaining logic in the root node is to handle when you use AUTOLOAD in a child class and the parent class also uses AUTOLOAD. This is even rarer, but it is still possible. As you say, it is important to trust a module to handle all edge cases so that you don't end up spending your evening debugging due to the module.

lodin

Replies are listed 'Best First'.
Re^5: A working strategy to handle AUTOLOAD, can(), and (multiple) inheritance without touching UNIVERSAL?
by SilasTheMonk (Chaplain) on Sep 01, 2009 at 06:38 UTC

    Actually I do have an empty DESTROY but I did not bother copying it. In my case if there is no DESTROY then the program tries to do stuff on a non-existent CGI::Application reference.

    The inheritence question is more interesting. Yes I can see my approach makes no special effort to handle inheritence. But actually I think it would work. Let me put my approach in words.

    1. Avoid AUTOLOAD except where it gives a big gain in loose coupling.
    2. Don't rely on someone else's module. The area is too complicated.
    3. This means you have to craft your own solution, but it is fairly simple.
    4. Define a DESTROY method as bad stuff happens otherwise.
    5. Define a semantically correct "can" function that either returns undef or a CODE ref.
    6. Define the AUTOLOAD function in the fairly standard way based upon the "can" function.
    7. If I were to write a derived class I would either inherit both "can" and "AUTOLOAD" and override less impactful functions; or I would override "can" in the same way and make use of SUPER::can where appropriate.
    8. I avoid multiple inheritence so I would make autoloading in a multiple inheritence scenario an absolute no.

      Don't rely on someone else's module. The area is too complicated.
      Interesting. This is exactly why I think a module is needed. It is too complicated to be reimplemented and at least my first version was flawed or incomplete. I'd be more inclined to trust a module if the documentation and test suite give the impression of the module being robust.

      This means you have to craft your own solution, but it is fairly simple.
      That sounds a bit contradictory. :-)
      Define a DESTROY method as bad stuff happens otherwise.
      How about return if $method eq 'DESTROY'; in AUTOLOAD?
      Define a semantically correct "can" function that either returns undef or a CODE ref.
      Would that include looking at UNIVERSAL::can to find "real" methods?
      Define the AUTOLOAD function in the fairly standard way based upon the "can" function.
      Someone might decide to overload can and use caller arbitrarily, which may break (since there is no uplevel function in Perl). One might do this to remove some methods in can from the public (they can of course still be called). Good idea or not; I'm not to judge. I think caller was the reason I moved the logic out from can and into a common routine shared between can and AUTOLOAD. That way if anyone overloads can they do not have to think about my AUTOLOAD implementation since AUTOLOAD does not call can and in can I can use goto &$next to make it fully transparent.
      I avoid multiple inheritence so I would make autoloading in a multiple inheritence scenario an absolute no.
      It's not harder to use next::method/next::can and mro::get_linear_isa/Algorithm::C3::merge than it is to use SUPER::foo/can('SUPER::foo') and Class::ISA::super_path (mro/Algorithm::C3/Class::ISA is only needed (?) when overloading AUTOLOAD). mro.pm is core since Perl 5.9.5.

      If you wanted to allow subroutine stubs in your classes (including any subclasses) you'd need to take some special care, I believe. This may be to break your first rule above, but still. The person who subclasses your class might not agree so if it can be solved I favor solving it. The problem is that UNIVERSAL::can returns a reference, but the subroutine it references is undefined, so AUTOLOAD will be invoked. So to avoid fatal recursion can may not return a reference to an undefined subroutine (i.e. stub). I think you may run into trouble with $self->SUPER::foo and/or $self->can('SUPER::foo') as well. ($self->SUPER::foo invokes AUTOLOAD only if it's a stub.)

      The reciprocal perspective is that you want to overload a method and use SUPER in a subclass to a class (that perhaps someone else wrote) that uses stubs to lazily provide methods. If AUTOLOAD would query can then you'd end up with a fatal recursion.

      Coincidentally, the design of Class::AUTOCAN implicitly handles stubs seamlessly. :-) If you want to lazily provide a method but still want to give it the precedence of a real method then you just do

      { package Foo; sub foo; sub bar { __PACKAGE__ }; # Handles &foo, and fallback for everything. AUTOLOAD { __PACKAGE__ } ## or, if it should can() everything: #use Class::AUTOCAN sub { # return sub { __PACKAGE__ }; #}; } { package Foo::Bar; our @ISA = Foo::; sub bar; # Lazily overload bar. # Handle &bar and provide fallback for &foo and &BAR. # &foo should not be called here since &foo is declared # and should be handled by Foo::AUTOLOAD. If &foo should # be handled here then a stub should have been declared # here. use Class::AUTOCAN sub { my $self = shift; my ($method) = @_; return sub { __PACKAGE__ } if $method eq 'foo'; # Beware: stub +. return sub { __PACKAGE__ } if $method eq 'bar'; return sub { __PACKAGE__ } if $method eq 'BAR'; return; # Let Foo worry about other methods. }; } my $o = Foo::Bar::; for my $method (qw/ foo bar BAR abc /) { my $code = $o->can($method); printf "%s => %-8s (can: %-8s)\n", $method, $o->$method, ($code ? $o->$code : ''), ; } __END__ foo => Foo (can: Foo ) bar => Foo::Bar (can: Foo::Bar) BAR => Foo::Bar (can: Foo::Bar) abc => Foo (can: )
      Maybe I should upload Class::AUTOCAN somewhere so that you can try it out and see if you find any bugs in it. I would appreciate any fire your or anyone else could put it under. :-) If it's not bullet proof then it's not worth having on CPAN.

      lodin

      Update: improved the example.

        Interesting. This is exactly why I think a module is needed. It is too complicated to be reimplemented and at least my first version was flawed or incomplete. I'd be more inclined to trust a module if the documentation and test suite give the impression of the module being robust.
        Yeah. If there was such a module I would use it. But if everyone followed my advice there would be no early adopters and so it would never reach the required maturity. I suspect all the perl brains (who could cut through this) are currently working on perl6.
        >>> This means you have to craft your own solution, but it is fairly simple. That sounds a bit contradictory. :-)
        Not at all contradictory. If you craft your own solution you are not trying to come up with an all encompassing solution but rather your are cutting your goals back to what matters in your circumstances.
        How about return if $method eq 'DESTROY'; in AUTOLOAD?
        Isn't this obscurantist? If you want to implement DESTROY why not just define one. Are you arguing that once you start using AUTOLOAD everything should pass through AUTOLOAD?
        Would that include looking at UNIVERSAL::can to find "real" methods?
        This is exactly what I do not trust. It seems that one class is trying to be very clever. It just feels wrong.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://792476]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (7)
As of 2024-03-28 13:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found