in reply to Re^2: Re-blessing || Re-constructing objects
in thread Re-blessing || Re-constructing objects

I suppose you could say that all OO is just a way to attach a dispatch table to some data structure. However, the other classes are not supposed to need to know what the actual data structure is, since they access it through methods. If you re-bless an object, your code (the part that does the re-blessing and the class you re-bless it into) will now break if the internals of the original class break, even if the API doesn't change.
  • Comment on Re^3: Re-blessing || Re-constructing objects

Replies are listed 'Best First'.
Re^4: Re-blessing || Re-constructing objects
by salva (Canon) on Apr 18, 2006 at 18:10 UTC
    no, please, don't misunderstand me, I am not advocating into reblessing objects wildly from one class into another. I am just saying that doing it in a controlled manner is an useful mechanism and it can be used without breaking encapsulation or any other OOP property.

    Those controlled manners are at least two:

    • Reblessing an object into a descendant class of its current class. For instance, when you get new information about the object (BTW, in C++ this is done all the time under the hood at object construction time).
    • using several packages to implement a unique class that can change its behaviour dynamically, for instance:
      class TheHulk; sub new { bless $self, $class; $self->go_normal; $self; } sub go_normal { bless $self, TheHulk::_normal; } sub go_green { bless $self, TheHulk::_green; } sub relax {} sub make_angry {} package TheHulk::_normal; sub run { ... } sub make_angry { $self->go_green; } package TheHulk::_green; sub run { ... } sub relax { $self->go_normal; }
      three packages are used, but conceptually is just one class, so there is no messing with the internals of one class from another and the reblessing is always done from inside the class not from the outside.
    • any other?

      I am just saying that doing it in a controlled manner is an useful mechanism and it can be used without breaking encapsulation or any other OOP property.

      Well said. Just because something is dangerous doesn't mean it can't be used in a positive way.

      ---
      $world=~s/war/peace/g

      It can't be done without breaking encapsulation. All of your examples require a class to know all about the internals of some other class. You may decide that's okay in your case, but it still loses the abstraction.

        Just out of curiousity do you consider "friend" classes to violate encapsulation?

        ---
        $world=~s/war/peace/g

        No. In my sample code there is only one class.