From: Logan Capaldo Date: 2006-05-09T05:19:56+09:00 Subject: Re: A major ruby annoyance! On May 8, 2006, at 4:10 PM, dblack@wobblini.net wrote: > Hi -- > > On Mon, 8 May 2006, Logan Capaldo wrote: > >> >> On May 7, 2006, at 5:00 AM, dblack@wobblini.net wrote: >> >>> Hi -- >>> On Sun, 7 May 2006, Logan Capaldo wrote: >>>> I would suggest using the attr_* methods or writing your own >>>> accessors for any case where you might need to access an >>>> instance varible >>>> @something = exp >>>> is probably a bad sign anywhere but initialize and/or >>>> def something=(x) >>>> ... >>>> end >>>> likewise a = @something should almost always be a = self.something >>> It all depends. The attr_* family uses instance variables to do >>> what >>> it does, but there's no reason that should be viewed as the only or >>> best or likeliest use of instance variables. It's layered on top of >>> a subsystem (instance variables) that have other uses too. >>> David >> I wans't suggesting only using ivars for accessors, but I believe >> strongly in the uniform access principle. Even if you using ivars >> for something completely internal that no one sees, you should >> still wrap the accesses to them in methods (private ones). > > But then you are suggesting that they only be used for accessors :-) > > I can't help feeling it's a lot of trouble to do this: > > class C > def initialize > self.container = [] > end > > private > attr_writer :container > end > > rather than: > > class C > def initialize > @container = [] > end > end > > if you're just using @container as a state variable here and there. > > I think the role of the uniform access principle here is open to > question. As I understand it, that principle states that the outside > user shouldn't be able to tell whether a value is stored or calculated > -- essentially, an attribute vs. the return value of a method call. > But instance variables are neither attributes nor methods; so they're > not really candidates for being evaluated for uniform/non-uniform > access. And Ruby's attributes *are* methods. To that extent, Ruby > actually enforces the UA principle; when you do this: > > obj.something > > you know that you've called a method. There's no other possibility, > so there's no opportunity for divergence of the interface. > > > David > > -- > David A. Black (dblack@wobblini.net) > * Ruby Power and Light, LLC (http://www.rubypowerandlight.com) > > Ruby and Rails consultancy and training > * Author of "Ruby for Rails" from Manning Publications! > > Paper version coming in early May! http://rubyurl.com/DDZ > Well at least if you do it my way, you don't get tripped up by typos, ;)