in reply to Is "ref($class) || $class" a bad thing?
Basically, that construct is saying "This method can be called as either a class or instance method". While this may be neat (for example, Test::Cmd takes advantage of this by inheriting from File::Spec), it's certainly not helpful in most cases.
But, I must take exception with one of the conclusions you're implying. The error in line 14 is caused by the fact that your new() method isn't verifying that it was actually passed anything. The better solution is:
package Foo; sub new { my $proto = shift || die "Must pass a class or object into new()"; my $class = ref($proto) || $proto; bless {}, $class; }
Of course, this still doesn't fully work because it doesn't take into account Foo::new( {} );, which will return an object blessed into the HASH class. So, maybe we should do something like:
package Foo; use Scalar::Utils qw( blessed ); sub new { die "Must pass a class or object into new()" unless @_; my $proto = shift; my $class = blessed($proto) or $proto; bless {}, $class; }
That should take care of most situations I can think of. But, we're just getting stupid. :-)
------
We are the carpenters and bricklayers of the Information Age.
Then there are Damian modules.... *sigh* ... that's not about being less-lazy -- that's about being on some really good drugs -- you know, there is no spoon. - flyingmoose
I shouldn't have to say this, but any code, unless otherwise stated, is untested
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Is "ref($class) || $class" a bad thing?
by hardburn (Abbot) on Jul 12, 2004 at 16:29 UTC | |
•Re^2: Is "ref($class) || $class" a bad thing?
by merlyn (Sage) on Jul 12, 2004 at 18:28 UTC | |
Re^2: Is "ref($class) || $class" a bad thing?
by stvn (Monsignor) on Jul 12, 2004 at 16:55 UTC | |
by chromatic (Archbishop) on Jul 12, 2004 at 23:31 UTC | |
by stvn (Monsignor) on Jul 13, 2004 at 01:11 UTC | |
by chromatic (Archbishop) on Jul 13, 2004 at 03:37 UTC | |
by adrianh (Chancellor) on Jul 17, 2004 at 14:31 UTC | |
by merlyn (Sage) on Jul 20, 2004 at 13:32 UTC | |
by adrianh (Chancellor) on Jul 20, 2004 at 16:46 UTC |