Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

(jeffa) Re: Replacing namespaces

by jeffa (Bishop)
on Dec 11, 2001 at 00:19 UTC ( [id://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!

jeffa

L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
F--F--F--F--F--F--F--F--
(the triplet paradiddle)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (7)
As of 2024-04-25 09:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found