The two main reasons to use accessors is to provide a checkpoint where data can be validated before being used by the class, and to allow the internal format of the data to change without having to change the interface.

Do you need those checks when you access the data internally?
If the data format changes internally, will it be a hardship to change the other methods accordingly?

The answer is usually no, removing the need to use accessors internally.


Incidentally, recent experience has taught me that using an accessor internally can prevent a class from being inherited.

A class I was using inherited from another class in order to override accessors in order to pre-process (encode/decode) the data being exchanged. This worked fine with the XS implementation of the base class, since it didn't use the accessor internally, but it failed with the PP implementation of the base class, since it used the accessor internally, causing the encoding/decoding to occur twice.

This is more of a lesson in the need to use composition instead of inheritance rather than a lesson against the internal use of accessors, but inheritance is misused in this manner so often that it should be taken in to consideration.

If you want to use accessors internally for whatever reason (say to reduce code duplication), it might be useful to have accessors for internal use and accessors for external use (sub accessor { &_accessor }).


In reply to Re: Does one encapsulate a class from itself? by ikegami
in thread Does one encapsulate a class from itself? by amarquis

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.