Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re^2: Reclassifying an object

by Amblikai (Scribe)
on Sep 29, 2015 at 11:25 UTC ( [id://1143336]=note: print w/replies, xml ) Need Help??


in reply to Re: Reclassifying an object
in thread Reclassifying an object

I follow you and thanks for your reply. I'm not sure how to go about reblessing the object though.

As i see it i could:

  • Have the constructor call the method to determine the class, and immediately rebless the object as some other class. The problem i see here is that now the parent class has to have knowledge of it's child classes which i think breaks inheritance?
  • Or i could interrogate the type in the main script and create a clone of a different (sub)class. This seems inefficient to me and it seems like i'm bringing the code out of the classes and into the main script.

Am i needlessly overcomplicating things?

I found this code: Stack Overflow But to be honest i'm having real trouble following what the user is doing here!

Replies are listed 'Best First'.
Re^3: Reclassifying an object
by choroba (Cardinal) on Sep 29, 2015 at 12:01 UTC
    I imagined the second solution:
    my $obj = 'Parent'->new; $obj->populate(@data); for my $child_class (@possible_child_classes) { if (my $new = $child_class->new_from_parent($obj)) { $obj = $new; last } } # Don't forget to handle the case that $obj hasn't changed.

    In fact, the only problem why this shouldn't go to the parent class is the array of possible child classes. So, get it from outside; the parent can insist on its children implementing a method:

    sub new_from_parent { die "Should be overriden.\n" } sub rebless { my $self = shift; my @possible_child_classes = @_; for my $child_class (@possible_child_classes) { # etc. using $self instead of $obj.

    And the code becomes

    my $obj = 'Parent'->new; $obj->populate(@data); $obj->rebless(@possible_child_classes);
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re^3: Reclassifying an object
by salva (Canon) on Sep 29, 2015 at 11:49 UTC
    The problem i see here is that now the parent class has to have knowledge of it's child classes which i think breaks inheritance?

    As Salvor Hardin used to say, never let your sense of morals prevent you from doing what is right!

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (6)
As of 2024-04-18 15:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found