John M. Dlugosz has asked for the wisdom of the Perl Monks concerning the following question:

I need to supply a callback function to an instance of my class. That function might decide to not handle it and defer to the built-in functionality, after looking at the arguments.

One approach is to have a special return value meaning "not for me".

Another approach, which is more flexible and good for a somewhat different class of problems, is to chain to the original (or earlier) function. The "hard way" is to set up my callback by getting the old value and saving that where my callback can see it, then setting my function as the new one to be called.

But I'm struck with how similar this is, conceptually, to "wrapper methods" and overrides of virtual functions in general. However, I don't want to derive a class to do it, and I want to supply the information per-instance.

But I can't help wondering if a similar mechanism would be useful for per-instance callbacks, either as a full-blown callback manager module, or at least employing these concepts in the design of how callbacks are supplied and possibly chained.

Anyone want to talk about it? Is there a better, modern, way to program callback features?

—John

Replies are listed 'Best First'.
Re: chaining callbacks
by GrandFather (Saint) on May 07, 2011 at 06:16 UTC

    Since you've already precluded my first thought (derived class implementation), how about a left field idea? Have the call back die with some "I don't do this stuff" string or object and have the call back caller figure it out. That way return results and normal execution are unaffected by the handling mechanism used for managing call back processing.

    True laziness is hard work
      I like the idea of separating out-of-band control returns from the normal return of a value. Perhaps this would be a good approach for Perl 6. But exceptions are too expensive and not intended as a "normal" control-flow mechanism.
Re: chaining callbacks
by anonymized user 468275 (Curate) on May 07, 2011 at 14:54 UTC
    Pass a code reference to the default function to the callback function? e.g.
    $self -> {CALLBACK} = sub { my $self = shift; my $default = shift; my @args = @_; ( "arg condition here" ) and return $default -> (@args); ... }

    One world, one people