in reply to Reclassifying an object

Hello Amblikai,

I would be interested to know why each data object’s class has to change. However, given that it does, I would prefer a design in which the client code knows only the parent class (i.e., the interface), and has no knowledge of the various child classes. (That is, child classes are treated as “implementation details.”) Here is a sketch of how this can be accomplished:

#! perl use strict; use warnings; package Widget { use Scalar::Util qw( blessed ); sub new { my ($class, $data) = @_; my $self = { Data => $data }; return bless $self, $class; } sub rebless { my ($self, $new_info) = @_; my $class = blessed $self; die unless $class eq __PACKAGE__; $self->{Info} = $new_info; if ($self->{Info} =~ /WXYZ/) { $class = 'Widget_A'; } elsif ($self->{Info} =~ /STUV/) { $class = 'Widget_B'; } else { die "Unrecognised class: $!"; } return bless $self, $class; } sub frobnicate { # my ($self) = @_; print "Implementation of frobnicate() for all Widgets\n"; } sub tweak { die "method tweak() must be overridden in child classes: $!"; } } #-------------------- package Widget_A { use parent -norequire, qw( Widget ); sub tweak { # my ($self) = @_; print "method tweak() for Widget_A objects\n"; } } #-------------------- package Widget_B { use parent -norequire, qw( Widget ); sub tweak { # my ($self) = @_; print "method tweak() for Widget_B objects\n"; } } #-------------------- # Client code #use Widget; my $setup_data = 'Setup'; my $object_1 = Widget->new($setup_data); $object_1->frobnicate(); my $new_info = 'WXYZ'; my $object_2 = $object_1->rebless($new_info); $object_2->tweak();

Output:

2:28 >perl 1387_SoPW.pl Implementation of frobnicate() for all Widgets method tweak() for Widget_A objects 2:28 >

(Of course, the Widget, Widget_A, and Widget_B packages should occupy separate .pm files. I’ve run them together into the “main” .pl file only for my convenience.)

The chief advantage of this design is that whenever a new Widget child class is added, the only existing code that needs to change is the rebless method in Widget.pm.1 Client code remains unaffected.

1Update: Widget.pm must also use each of its child classes.

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,