* Graeme McLaren <[EMAIL PROTECTED]> [2006-06-08T05:44:05]
> Hi all, I've just been reading a bit about accessor get/set methods.  I 
> have a method:
> 
> sub even{
>    my $self = shift;
>    my $even   = shift;
> 
>    $self->{_even} = $even if defined($even);
>    return $self->{_even};
> }
> 
> 
> This basically does what a get and set method would do.  So why would I 
> need a set/get methods?  This value is passed to the object like so:

It's a question of style, largely.  Some people prefer their code to be
very clear about whether your getting or setting.  Using explicit set and get
methods can also help prevent bugs; you won't accidentally make a read-only
value writeable, because you will avoid writing a set_ro_value method -- if you
only have a get-and-set ro_value method, you might forget to special-case it to
be get-only.

Also, you'd probably avoid bugs like the one you introduced above.  What
happens if I want to clear the even value?

  $obj->even(undef);

This does not affect the value; I can't undef even.

You probably wanted:

  sub even {
    my $self = shift;

    return $self->{even} unless @_;
    return $self->{even} = shift @_;
  }

-- 
rjbs

Attachment: signature.asc
Description: Digital signature

Reply via email to