Sean Quinlan wrote:
>
> On Fri, 2003-08-15 at 15:46, [EMAIL PROTECTED] wrote:
> > If it DOES need an object, I don't quite understand why
> > you cant do the bless in new, call gripe, and just return
> > the object when you're done.
>
> Only because it felt odd and out of order to create the object before
> it's attributes and such have been validated.
I don't know of any clean rule of thumbs,
but if you have an attribute set routine
with its own validation code, then it
makes sense that your constructor takes
advantage of that.
sub set_age
{
my ($obj,$age)[EMAIL PROTECTED];
if(($age<0) or ($age>120))
{
$obj->gripe("wacko age");
}
else
{
$obj->{age}=$age;
}
}
# doing this from memory,
# an exercise for the reader to check for coding errors.
sub new
{
my $class=shift;
my $obj=bless{},$class;
my %att_vals = @_;
# any attributes that MUST be set first before all
# other attributes are set would be done here.
# assume the 'gripe_flag' attribute must be set
# before any other attributes are handled.
my ($first_att,$first_val)=delete($att_vals{gripe_flag});
if($first_att)
{
$obj->{$first_att}=$first_val;
}
# now call the attribute handler, if it exists, to
# set any attributes passed in. the handler will do the
# range check. If no handler, set the attribute value raw.
while(my($att,$val)=each(@_))
{
my $method = 'set_'.$att;
if($obj->can($method))
{ $obj->$method($val); }
else
{ $obj->{$att}=$val; }
}
}
This constructor will call set_"attribute" method
if it exists so the method can do whatever validty
check it needs to do. if a set_"attribute" method
does not exist, it just sets the raw attribute without
any checks.
The pain about OO is that you usually want your public
attributes to have get/set methods to range check anything
that a user might pass in. But you don't want to be tied
to having ALL your attributes have get/set if they're
internal use only.
The above constructor will call the set_"attribute"
if it exists, and just set it raw if it doesn't.
this way you can add new attributes without having
to fiddle with get/set methods to see if tehy work.
in the end, OO is always messy.
Greg
_______________________________________________
Boston-pm mailing list
[EMAIL PROTECTED]
http://mail.pm.org/mailman/listinfo/boston-pm