[Pharo-users] Accessors vs instance variables

Craig Johnson craig at hivemind.net
Fri Oct 2 02:59:27 EDT 2015


Hi,

This is a bugbear for me.
On 2015/09/30 09:35 PM, Lyn Headley wrote:
> Hello,
>
> As I understand it, in Smalltalk, the instance variables of a class C 
> are "protected" - able to be referenced by methods of C or its 
> subclasses, but not by other objects. This is a useful feature as it 
> clearly points out which pieces of data are not available to other 
> objects, and thereby simplifies code.
>
> However, I am often unsure of whether to use this feature or not, as 
> it conflicts in my mind with the practice of using accessor methods. I 
> like accessor methods because they make it easy to change behavior 
> later -- If I have a dozen calls to an accessor method, then I only 
> need to change it in one place. If these were instance variable 
> references, I would have to do more work. The disadvantage of accessor 
> methods is that they obscure the protected status of data -- it 
> becomes unclear how protected an instance variable is meant to be. 
> (Accessors also make it harder for me to find users of the data when 
> browsing, when there are senders from totally unrelated classes, 
> although I suspect I have just not figured out how to browse scoped in 
> the right way for this).
>
> It occurs to me that a tool could be (easily?) developed that would 
> solve this problem. It would take existing variable references and 
> turn them into calls to accessor methods. That way, I could have 
> protection when I want it, and easy ability to change code as well. 
> Does something like this exist, or is it feasible to build?
>
> How do others think about this issue?
>
> -Lyn
>
I'm old-school OO and don't like accessor methods at all.  They break 
encapsulation, they cloud the object interface, and most importantly 
they allow bugs to be introduced by undocumented modification of the 
object's internal state.

Nobody has shown me a good reason for their existence and I never use 
them except where I'm forced to use them in Spec and Glorp.

Craig

PS:  I'm forced to use them in C# as well (my day job).  Because in C# 
it's only way to promote a local variable to a property which is 
required by most frameworks.




More information about the Pharo-users mailing list