in reply to Re: Re: Re: Re: Reducing Perl OO boilerplate
in thread Reducing Perl OO boilerplate
Mammoth constructors have absolutely nothing to do with inheritance. Inheritance is, for all practical purposes, determined when using the two-part form of bless. Nothing more, nothing less. Here's an example:
package Foo; sub new { my $class = shift; my %options = @_; my $self = {}; # Do 1000 lines of stuff with %options return bless $self, $class; } package Bar; use base 'Foo'; # A bunch of stuff goes here, but NO new() method! package main; my $object = Bar->new( # A bunch of named parameters go here );
Named parameters, inheritance, and a bunch of stuff in a constructor. No sweat.
Now, if you wanted to have all your objects use a very basic constructor, let me show you the basics of what I do:
package My::Base::Class; sub new { my $class = shift; my $self = bless {}, $class; (@_ % 2) && die "Odd number of parameters passed to new()"; my %options = @_; while (my ($k, $v) = each %options) { next unless $self->can($k); $self->$k($v); } return $self; }
I assume that a mutator has been created with the same name as the parameter being passed in and that you want to assign the value to the attribute corresponding to the mutator. Very simple, very easy ... no fuss - no muss. If everything inherits from My::Base::Class, then everything gets that constructor. Named parameters, inheritance, and no boilerplate constructor.
Now, you're going to want more flexibility than that, so you might create an init() hook. You might auto-generate mutators based on a method call at compile time. There's all sorts of sugar you can add to this. But, at the heart, this is all you really need.
------
We are the carpenters and bricklayers of the Information Age.
Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Re: Re: Re: Re: Re: Reducing Perl OO boilerplate
by flyingmoose (Priest) on Feb 18, 2004 at 20:25 UTC |