I've been reading up on Perl/OO lately and there's one thing (okay, there's a lot of things, but this one mostly, right now) that is bothering the heck outta me: getters and setters for object data.

I understand the idea of not having the object's data acessed directly (like $self->{'myDataField'}) because:

So, the solution to this is accessing data or setting it via methods, right? I'm clear on that too. Now, I've seen a getter/setter in OO tutorials, one written for each attribute. Then I've seen the module class::accessor which auto-generates them for you, and then calls a generic get/set for each method (so you can change the underlying data structure by overrideing get/set in your subclass).

Now here is where I'm confused: Why do you need a different method for each bit of data? The first thought in my mind after reading the class::accessor documention was why not do something like this:

$myObject->getValue("myDataField"); $myObject->setValue("myDataField","New Data");

or even ...

$myObject->dataValue("myDataField","")

Where filling in the second value makes it a setter, a blank or non-existant 2nd field would be a getter.

This type of set up should solve the problems of encapsulation, and of being able to change the way data is stored later, even via subclassing if a user desires. But something tells me that I must be missing something ... or else things like class::accessors wouldn't exist.

So, here's the query: Is there a reason I shouldn't do it the way I've just outlined above? If there is, I'd love to know it. Pehaps I've misunderstood encapsulation, or OO in general. I'm -very- new to OO-style programing.

I hope someone here can enlighten me :-)

# theAcolyte


In reply to OO Getters/Setters by theAcolyte

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.