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
- extensibility - need to generalize First, Second,
Third, etc.
- 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)
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.