Clashes between functional and OO worlds

ferreira on 2008-05-01T02:37:56

In refactoring some code, I opted for turning "warn/carp" calls into method calls "$self->carp". This way the objects could act by themselves (using CORE::warn/Carp::carp) or cooperate with others (via a closure).

sub carp {
    my $self = shift;
    my $on_warn = $self->on_warn;
    if ( $on_warn ) {
         $on_warn->(@_);
    } else {
         Carp::carp(@_);
    }
}

It turned out that naming the method the same as a function was a bad idea (at least in the transition to the fully refactored code). The simple application used some simple hierarchies, and when I "fixed" the superclasses as in:

package Parent;

sub carp {
    ...
}

I found after some perplexity that in the children, code like that:

package Child;

use base qw( Parent );

use Carp qw( carp );

...
   $self->carp("message");
...

emitted strange messages like:

Parent=HASH()message

because $self->carp("message") resolved to Carp::carp( $self, "message" ) as Carp::carp had been exported to Child overriding the method I was expecting to inherit.

That's what we earn because methods are just subs.


Don't import

ChrisDolan on 2008-05-02T02:14:04

If you simply change the "use" line to

  use Carp qw();
then this problem will go away.