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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |