Here's the question you have to ask yourself - how often do you expect to be changing the values of an attribute? Personally, when I create a circle, I don't expect to be changing its radius. I definitely don't expect to set its area. I already created the damn thing - why should I have to tell it how big it is?? It has eyes and a brain - it should tell me! Maybe something like this would be more to your liking:
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; }
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.

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.


My criteria for good software:
  1. Does it work?
  2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?

In reply to Re: The Accessor Heresy by dragonchild
in thread The Accessor Heresy by Roy Johnson

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.