http://qs321.pair.com?node_id=219867


in reply to Re: Re: Tutorial: Introduction to Object-Oriented Programming
in thread Tutorial: Introduction to Object-Oriented Programming

I'd be interested to hear your thoughts on using lvalue subs for the accessor/mutators?

Don't like them. No sir! Don't like them one bit.

For me the problem with lvalue subs is that they expose your object implementation just a little bit too much. Consider:

use strict; use warnings; my (%Foo, %Bar); sub foo : lvalue { $Foo{+shift} }; sub bar { my $key = shift; $Bar{$key} = shift if @_; $Bar{$key}; }; foo("apples") = 12; foo("pears") = 0; print foo("apples"), "\n"; print foo("pears"), "\n"; bar(bananas => 3); bar(oranges => 18); print bar("bananas"), "\n"; print bar("oranges"), "\n";

Now, what happens if I want to prevent negative values being assigned to the hashes. With bar() it's trivial.

sub bar { my $key = shift; if (@_) { die "no negative numbers" if $_[0] < 0; $Bar{$key} = shift; }; $Bar{$key}; };

With foo... it isn't trivial.

It's possible with a tied hash - but it's not simple. As soon as you need to do things with the values you are assigning (check them for validity, transform them, etc.) things suddenly get hard. You can end up with a separate tied class for each attribute.

When you get to this stage "normal" subroutines look good again - but then you're changing your API. Nasty. Best to stick with normal subroutines (be it perls all-in-one or separate setter/getter) from the start.

I really hope that perl6 takes a lesson from Eiffel and makes class attribute access and method calls look the same - that way all this nonsense can go away. Lexical subs used in this way are really just syntactic sugar for a $hash->{attr} and should be avoided most of the time (IMHO of course :-)


Updates