|We don't bite newbies here... much|
The Accessor Heresyby Roy Johnson (Monsignor)
|on Nov 28, 2005 at 16:26 UTC||Need Help??|
It is important to be aware that I am neither steeped in OO theory nor have I amassed a great deal of experience from which I can speak with authority. Having limited exposure to what's established means I might have fresh perspective, but I might also just fall right into a pit. Only an innocent child could get away with such blasphemy. God bless them all. Amen..
Having devoted more time to meditation and Thanksgiving on the topic of accessors, I believe I understand what it is that makes accessors rankle so much. The common practice of having setters and getters is not an OO practice. It's a hybridized thing that, like many such practices, is probably a pragmatic decision to reduce overhead compared to doing it "the right way".
In OO, things that you interact with are supposed to be objects, and you interact via their methods. Accessible properties are things that you interact with, but they often aren't implemented as objects, and their methods are owned by their parent objects.
Let's consider a Circle object. It's got properties like Area, Radius, and Circumference. (Interestingly, they're all different views of the same fundamental property.) The usual approach might be to have methods setArea, getArea, setRadius, etc. Notice that those names look like classical procedural programming names: what they operate on is part of their name, rather than being the object that owns the method.
An OO approach would be to have the properties be "sub-objects", and the accessors would be called like $myCircle->Area->set(5). You can see that Area could be either the sub-object itself (see tie for Perlish, encapsulated objects), or a function returning the sub-object, depending on your philosophy. Once I started thinking of properties as sub-objects, I found myself preferring method-returning-object over a distinct syntax for returning properties.
Now, since we've got three sub-objects with the same interface (set of methods), it seems reasonable to have a virtual class that defines that interface: a setter-getter scalar class. As it happens, such a virtual class is already defined for us by Perl. It's the scalar class we can tie to. However, the more I thought about it, the less useful it seemed to actually provide a tie-able interface to properties. It was just an interesting side-note.
Update: Well, I had included some example code, but a fat-fingered update ended up deleting it. Probably just as well; it distracted people from the point more than it helped them understand it. The point is: there is a more properly OO approach, but it involves some programming and performance overhead.