in reply to Reblessing yourself

Reblessing yourself is a fairly common thing, although I'm not sure I've seen it used in exactly this way. The more common use for reblessing yourself is if you don't know exactly what type of object you will be retrieving until you've retrieved some information about it (think of a database table containing 'objects' that includes a field describing the type of object).

Just recently in fact I was working on some code that did something along these lines:

package MyApp::Object; use base qw( Class::Accessor::Fast ); use Carp qw( croak ); sub new { my $self = shift::SUPER->new( {} ); $self->load_config_file( shift() ); my $type = join( '::', ref( $self ), $self->config->{ 'type' } || 'General' ); eval "use $type"; if ( $@ ) { croak "Couldn't load $type: $@" } bless( $self, $type ); return $self; }

This worked pretty well for the application I needed it for, and it allowed other code to very simply instantiate new objects without worrying about what type they should be.

The only downside I can see to your plan is that if the two classes have drastically different methods, you will probably find that people are tending to wrap them up in code like this:

if ( $obj->isa( 'Product::Real' ) ) { # do some real stuff } else { # do some potential stuff }

Simply because the differences in the classes causes people to think of them as entirely separate entities, and if people are doing this anyway, does $obj->isa( 'Product::Real' ) really save you anything over $obj->is_real?


We're not surrounded, we're in a target-rich environment!

Replies are listed 'Best First'.
Re^2: Reblessing yourself
by Ovid (Cardinal) on Apr 17, 2007 at 12:29 UTC

    Your points are taken and are definitely valid. As for your final question where you asked if $obj->isa( 'Product::Real' ) really saves anything over $obj->is_real, I would argue 'yes'. By not hardcoding class names I'm not constrained to a type. As a general rule, for OO programming, it's more important to rely on an object's cabalities rather than its type. Regrettably, Perl's limited introspection capabilities makes this a bit problematic, but that's a rant for another day :)

    Cheers,
    Ovid

    New address of my CGI Course.