From: Nat Pryce Date: 2002-11-01T01:42:37+09:00 Subject: Re: method-call style (was Re: Snippet: Tiny Featureless Ruby Web Server) On Thu, 2002-10-31 at 16:04, Albert Wagner wrote: > On Wednesday 30 October 2002 12:13 pm, Nat Pryce wrote: > > On Wed, 2002-10-30 at 17:38, William Djaja Tjokroaminata wrote: > > > dblack@candle.superlink.net wrote: > > > > I don't think one should make that assumption; it's awfully rigid. I > > > > might have: > > > > > > > > def stuff=(x) > > > > @thing = x > > > > end > > > > > > > > def stuff > > > > @thing > > > > end > > > > > > > > which is a dinky example at best... but meaning there is no necessary > > > > connection between the methods and the implementation. > > > > > > Well, it looks like a contrieved example, so it is really a matter of > > > personal style/convention. But now suppose that someone really writes a > > > code like above in a class, and I want to derive a new class from it, and > > > I need to access "the object logically represented by > > > stuff/thing". In my derived class, should I use "@thing" or should I use > > > "self.stuff"? > > > > Definitely use self.stuff to avoid breaking encapsulation. > > > > Imagine if the class was instead: > > > > def stuff=(x) > > @thing = x + 1 > > end > > > > def stuff > > @thing - 1 > > end > > > > > > Using @thing as a synonym for self.stuff would give the wrong result. > > Of course they give different results: @thing is a state variable, stuff= > modifies the state variable, and stuff is simply an algorithm that happens to > utilize the state variable. Assuming that stuff and @thing are synonymous is > what is wrong. Exactly my point! And it looks like a trivial point when illustrated with the code above. However, the point is as valid, although much less obvious to many programmers, when illustrated with David Black's original code, which was a direct assignment to and return from an instance variable. And the point is even less obvious when the accessor functions have the same name as the instance variable: def stuff @stuff end def stuff=( new_stuff ) @stuff = new_stuff end Cheers, Nat. -- Dr. Nathaniel Pryce, Technical Director, B13media Ltd. Studio 3a, 22-24 Highbury Grove, London N5 2EA, UK http://www.b13media.com