TheDamian suggests the use of get_foo and set_foo.This is because you have some attributes for which there will be a get_foo but no set_foo so the example was that a foo sub that is both a getter and setter has no way to indicate that you can not actually set foo, because if it dies then you have to wrap all your get/setters in eval { ... } and nobody wants that.
package Foo; use Readonly my $SPAM_FACTOR = 22; use Readonly my $SPAM_FUDGE = 42; # seasonally adjusted # cause-cause-bundles-of-problems constructor sub new { bless {spam=>4} , shift } # you can get or set bar with $that->bar sub bar { my ($this, $newbar) = @_; if (@_) $this->{bar} = $newbar; return $this->{bar}; } # you can't set baz, because it's derrived automatically from other at +tribute sub baz { my ($this) = @_; # just ignore @_ ... perhaps warn "you cant change baz" return $this->{spam} * $SPAM_FACTOR + $SPAM_FUDGE; } # some time later pacakge main; my $foo = Foo->new(); $foo->bar( 'moose' ); # neat, bar is moose $foo->baz( 'shoe' ); # not so much, worst of all, it looks right! printf "I have a lovely foo, it has %s bar and %s baz " , $foo->bar, $ +foo->baz; # hey! where's my shoe!?
if you use the get_bar and a set_bar convention, perl will complain bitterly when you call set_baz when the pacakge Foo does not provide one and you'll know straight away that you can't set_baz after all.
In reply to Re: Method Chaining and Accessors
by f00li5h
in thread Method Chaining and Accessors
by linenoise
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |