On 6/8/06, Ricardo SIGNES <[EMAIL PROTECTED]> wrote:
* 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


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2 (GNU/Linux)

iD8DBQFEiBrL5IEwYcR13KMRAnUiAJ9jORCdmqcxxvJSLnzfg2B0BXJdMACZAU3v
H8WkVST4w7lrACbWr2hdtLY=
=7rTT
-----END PGP SIGNATURE-----




i prefer the return once method:

sub foo
{
   my $self = shift;
   if (@_ == 1) { $self->{'foo'} = shift; }

   return $self->{'foo'};
}

--
Anthony Ettinger
Signature: http://chovy.dyndns.org/hcard.html

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to