[LRUG] attr_accessor parsed as a method variable when setting with a get

Graham Ashton graham at effectif.com
Wed Sep 21 03:48:21 PDT 2011


On 21 Sep 2011, at 11:31, Tom Stuart wrote:

> I like this because a) it encapsulates access to that piece of state, in case I want to provide a default or otherwise wrap reads/writes to the instance variable, and b) instance variables are ugly innit.
> 
> But if you like reading/writing instance variables in your methods, perhaps for Nebulous Performance Reasons, that's fine too.

Nice summary.

I've benefitted enough times (normally when refactoring classes) over the years from calling the accessor methods to feel that it's well worth it.

Once you've defined the accessor, consistency and predictability is also a good reason to use it.

In Python once you've defined the setter, it automatically gets called on assignment. In other words, the syntax for calling the setter is identical to the syntax to setting the instance variable. This has always struck me as a brilliant piece of design. What's nice about that is you don't have some code calling the accessor, some code updating the instance variable directly, simply because people have different styles, preferences or expectations.

In Ruby I stick to the convention instead.


More information about the Chat mailing list