in reply to Re: Perl OO and accessors
in thread Perl OO and accessors

but then you could use the magic of lvalue subs and tie to let you replace these 4 functions with 2 accessors

Using lvalue subs for accessors isn't generally a good idea. For instance, what would you do with $c->area = -42? And, how do you go back and change the interface later to avoid lvalue subs?

-sauoq
"My two cents aren't worth a dime.";

Replies are listed 'Best First'.
Re^3: Perl OO and accessors
by Zaxo (Archbishop) on Nov 29, 2005 at 08:47 UTC
    . . . what would you do with $c->area = -42?

    use Math::Complex;

    ;-)

    After Compline,
    Zaxo

Re^3: Perl OO and accessors
by Aristotle (Chancellor) on Nov 29, 2005 at 04:16 UTC

    what would you do with $c->area = -42?

    What you do with $c->set_area( -42 )?

    how do you go back and change the interface later to avoid lvalue subs?

    How do you go back and change the interface later to avoid set_foo methods?

    Makeshifts last the longest.

      What you do with $c->set_area( -42 )?

      Maybe I'm missing something. Say that I implemented set_area as

      sub set_area { my $self = shift; my $area = shift; die "Area must be non-negative." unless $area >= 0; # ... }
      How do you do the same with an lvalue sub?

      How do you go back and change the interface later to avoid set_foo methods?

      You don't. But, that's okay because you never have a need to.

      -sauoq
      "My two cents aren't worth a dime.";
      

        How do you do the same with an lvalue sub?

        You return a tied value. Ugly, slow, and doable. fergal did say <q>Neither of these expose an attribute, despite how it looks.</q>

        You don’t. But, that’s okay because you never have a need to.

        Why then would I ever have a need to go back and avoid lvalue subs?

        Makeshifts last the longest.

Re^3: Perl OO and accessors
by fergal (Chaplain) on Nov 29, 2005 at 11:09 UTC

    That's why I said lvalue subs and tie.

    You don't think I'd write all the spiel about irrevocable exposure and then go and suggest a method that is irrevocable.

    The technique involves returning a tied lvalue which then calls a setter method with the new value. All this can be hidden behind a use statement. See Class::Accessor::Lvalue for an example.