From: Brian Candler Date: 2003-06-25T21:39:04+09:00 Subject: Re: protect parents from children On Wed, Jun 25, 2003 at 08:38:57PM +0900, Simon Strandgaard wrote: > > However, the terms 'parent' and 'child' refer to classes, whereas @value > > is an instance variable. You're modifying an object of class B, which > > contains an attribute @value that B just happens to have inherited from > > its superclass, A. The values of instance variables are part of the > > object, not the class. > > Yes.. I found out it works like that. What I want is know: Is it possible > to make A#value private, so that it appears to be readonly within B ?? No, because an instance variable has no concept of "which class it came from". Suppose I write: class A def initialize(x=nil) @var = x if x end end class B < A def reset(x) @var = x end end # Now I do: a = A.new(99) # @value=99 b = B.new b.reset(99) # @value=99 Notice that @value was set from class A in the first example, and from class B in the second example. The compiler cannot know that @value "belongs" to class A or class B, because it doesn't; it belongs to the object (a or b), not the class. I think you will find Ruby encourages a different type of programming than you may be used to. Instead of expending effort putting up firewalls so that other pieces of code cannot do what they want, you expend effort writing programs that work instead :-) The whole 'subclassing' model is pretty flawed anyway. I find now that I almost never use it; rather, I use the delegator pattern (an object of class X *contains* an instance of class Y, rather than is subclassed from it). Problems seem to decompose much more naturally this way, and it's much easier to make use of the individual parts and bolt them together in different ways. Regards, Brian.