Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

(jeffa) Re: Replacing namespaces

by jeffa (Bishop)
on Dec 11, 2001 at 00:19 UTC ( #130764=note: print w/replies, xml ) Need Help??

in reply to Replacing namespaces

Interesting code you have there - i can't tell if it's a hack on the decorator pattern or maybe even the state pattern. At any rate, i think i see what the goal is:

You instantiate the First class and test to see if it does the job, if it doesn't, revert to the Second class. This is cool, but it's a maintenance nightmare should you decide to add a Third, or a Fourth, ... all the way to the Nth possible class.

I rewrote your code and added some tests - here is the solution domain:

0-5: fail 6-9: second handles 10-: first handles
And the code:
use strict; use Data::Dumper; package First; sub new { my $class = shift; my $self = { foo => 'bar' }; return bless $self, $class; } sub test { my $self = shift; my $arg = shift || 10; return ($arg > 9) ? "okay" : bless $self, 'Second'; } package Second; sub new { my $class = shift; my $self = { foo => 'qux' }; return bless $self, $class; } sub test { my $self = shift; my $arg = shift || 4; return ($arg > 5) ? "okay" : undef; } package main; my $arg = shift || 10; my $t = First->new(); if (ref $t->test($arg)) { warn "first failed, trying second..."; die "second failed" unless $t->test($arg); } print (ref $t, " passed\n"); print Dumper $t;
Try it out. Notice the very last expression which outputs the Dump of the object - notice how even though it might belong to package First or Second - $self is the same. That may or may not be a problem for you, because the technique to change $t from First to Second only changes it's package, not it's attributes.

In conclusion, the only two problems i see are

  1. extensibility - need to generalize First, Second, Third, etc.
  2. not inheriting attributes from oringal class - but this might your 'feature' ...
Three cheers for flexiblity!


(the triplet paradiddle)

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (9)
As of 2021-05-12 07:12 GMT
Find Nodes?
    Voting Booth?
    Perl 7 will be out ...

    Results (125 votes). Check out past polls.