in reply to Method Chaining and Accessors
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Method Chaining and Accessors
by doom (Deacon) on Apr 05, 2007 at 23:48 UTC | |
by TGI (Parson) on Apr 06, 2007 at 20:36 UTC | |
by f00li5h (Chaplain) on Apr 06, 2007 at 02:36 UTC | |
by doom (Deacon) on Apr 11, 2007 at 19:44 UTC | |
by f00li5h (Chaplain) on Apr 12, 2007 at 02:28 UTC | |
by doom (Deacon) on Apr 12, 2007 at 16:14 UTC | |
|