Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
use strict; use warnings; use feature 'say'; package Foo { sub new { my $pkg = shift; return bless {}, $pkg } sub frob { my $self = shift; $self-> foo( \&cb ) } sub blurt { my $self = shift; $self-> foo( 'cb' ) } sub foo { my ( $self, $cb ) = @_; $self-> $cb } sub cb { my $self = shift; say ref $self, ' ', __PACKAGE__ } }; package Bar { our @ISA = ( 'Foo' ); sub cb { my $self = shift; say ref $self, ' ', __PACKAGE__ } }; my $foo = Foo-> new; my $bar = Bar-> new; $foo-> frob; $bar-> frob; $foo-> blurt; $bar-> blurt;
It says (which doesn't require explanation, that's not the question):
Foo Foo Bar Foo Foo Foo Bar Bar
The callbacks in above classes look the same for the SSCCE, but let's pretend they are different, and I only want to change callback behaviour in derived class.
In practice, there are multiple changes, including some of the "callbacks". My class inherits from CAM::PDF, one of its "cornerstones" is the traverse method, which is called by a few specialized methods with a callback as an argument. e.g., verbatim, a short one:
and relevant line in traverse is:sub setObjNum { my $self = shift; my $objnode = shift; my $objnum = shift; my $gennum = shift; $self->traverse(0, $objnode, \&_setObjNumCB, [$objnum, $gennum]); return; }
$self->$func($objnode, $funcdata);
Is calling a callback i.e. code reference as method on an instance the accepted and OK practice, to begin with? In derived class, I'm now in some mess of a situation.
Should I override every "specialized" method (even those I didn't intend to) and replace coderefs with strings? Will it hurt performance, and how much?
Maybe I can fix all that at the "central location" (i.e. traverse) without touching every "specialized method" -- to convert a coderef to sub name? How to do that using Perl built-in (or core) functions? Would this solution be better (faster, cleaner, etc.)?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Methods, within a class, pass callbacks; how to deal with that in derived class?
by hv (Prior) on Oct 13, 2024 at 15:48 UTC | |
|
Re: Methods, within a class, pass callbacks; how to deal with that in derived class?
by karlgoethebier (Abbot) on Oct 14, 2024 at 07:16 UTC | |
|
Re: Methods, within a class, pass callbacks; how to deal with that in derived class?
by Anonymous Monk on Oct 13, 2024 at 13:32 UTC |