Beefy Boxes and Bandwidth Generously Provided by pair Networks DiBona
more useful options
 
PerlMonks  

Re: Safer monkey-patching

by dwalin (Monk)
on Jan 19, 2012 at 06:30 UTC ( #948697=note: print w/ replies, xml ) Need Help??


in reply to Safer monkey-patching

In my experience, monkey patching usually is not worth its trouble. The problem you describe above I would solve by subclassing + duck typing: in Example::ErrorList, provide a method that returns list item class name, and instantiate objects of that name. This way you can subclass both Example::ErrorList and Example::Error in a "clean" way.

Like this:

package Example::ErrorList; sub list_item_class { 'Example::Error' } sub new { my ($class) = @_; my $item_class = $class->list_item_class; my $self = bless {}, $class; $self->{items} = [ map { $item_class->new($_) } @seed_list_or_some +thing ]; return $self; } package Example::Error; sub as_string { die "as_string should be implemented by subclass"; } sub asplode { my ($self) = @_; die "BANG! ".$self->as_string; } package My::AwesomeErrorList; use base 'Example::ErrorList'; sub list_item_class { 'My::AwesomeError' } package My::AwesomeError; use base 'Example::Error'; sub as_string { # Actually implement it }

You also have a typo: my $self = @_; won't work the way you expect.

Regards,
Alex.


Comment on Re: Safer monkey-patching
Select or Download Code
Re^2: Safer monkey-patching
by moritz (Cardinal) on Jan 19, 2012 at 08:07 UTC
    in Example::ErrorList, provide a method that returns list item class name, and instantiate objects of that name.

    You can also make that an attribute (plus accessor, if you want), so that subclassing isn't even necessary. If you use blessed hash references as objects, and do not create the hash key in the default case, there's not even a memory penality to be paid unless you deviate from the default.

    An example for a read and write accessor could be

    sub error_class { my $self = shift; my $default = 'Example::Error'; if (@_) { my $new = shift; if ($new eq $default) { delete $self->{error_class} } else { $self->{error_class} = $new' } } $self->{error_class} // $default }

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (6)
As of 2014-04-20 10:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (485 votes), past polls