in reply to The Accessor Heresy
You'll note the stretch() subroutine - that allows you to alter the size of the circle. But, instead of re-setting the radius, you're $cicle->strech( 3 )'ing, which makes more sense from a reader's point of view.package Circle; my $PI = 3.1415926; sub new { my $class = shift; my ($radius) = @_; return bless { radius => $radius }, $class; } sub radius { my $self = shift; return $self->{radius}; } sub area { my $self = shift; return $PI * $self->radius ** 2; } sub stretch { my $self = shift; my ($amount) = @_; $self->{radius} += $amount; return; }
Most accessors in Perl are there for the object itself, not for the client. In Ruby, for instance, I would write that Circle class as so:
class Circle attr_reader :radius @@PI = 3.1415926 @@PI.freeze def initialize ( r = 5 ) @radius = r end def area @@PI * @radius * @radius end def stretch ( amount = 1 ) @radius += amount end end
@x is an instance attribute and @@X is a class attribute. freeze() marks it as a constant. The ( x = 1 ) in the method declarations are default values.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: The Accessor Heresy
by QM (Parson) on Nov 28, 2005 at 17:04 UTC | |
by dragonchild (Archbishop) on Nov 28, 2005 at 18:52 UTC | |
|
Re^2: The Accessor Heresy
by Roy Johnson (Monsignor) on Nov 28, 2005 at 17:00 UTC | |
by dragonchild (Archbishop) on Nov 28, 2005 at 18:55 UTC | |
by Roy Johnson (Monsignor) on Nov 28, 2005 at 19:34 UTC | |
|
Re^2: The Accessor Heresy
by sauoq (Abbot) on Nov 28, 2005 at 17:12 UTC | |
by dragonchild (Archbishop) on Nov 28, 2005 at 18:49 UTC | |
by itub (Priest) on Nov 28, 2005 at 20:51 UTC |