Thinking about constructors again

pdcawley on 2002-03-15T09:38:09

I've been thinking a bit more about constructors and the fact that being able to do Class->new(file => 'blah') is a really handy thing to do. And then I thought about Perl's diverse object representation model. So, here's the base class 'new' I'm thinking of moving to. Note that it's representation independent and, because I did the 'composed method' thing, it's easy to override small parts of the implementation. sub new { my $proto = shift; return $proto->new_with_args(@_) if @_; $proto->make_a_new_one->init; } sub make_a_new_one { my $proto = shift; bless {}, ref($proto) || $proto; }

sub new_with_args { $self->throw(Exception->new("Can't handle args")) } sub init { }
Note that, if you have an object that's better represented as an arrayref, say, just do sub make_a_new_one { my $proto = shift; bless [], ref($proto) || $proto; } And it will Just Work.

And yes, I *know* it looks like an awful lot of work just to make an object, but it's all about the intent baby.