Hi,
I am sorry that I don’t know much about the OO theory (haven’t read that
Bertrand Meyer’s book). But the argument below made me think of two
questions:
-
From a general OO theory point of view, is it good if a subclass makes
a variable more restricted? In the example below, for class A, @a is
protected, but for class B < A, @a is private.
-
If the answer to 1) is yes, or even just allowable, then probably is it
just a matter of implementation? For example,
Suppose each class has two hashes: one for protected variables and one for
private variables. When symbol “@var” is encountered (as rvalue), the
order of search is as follows:
1) Search in the private hash.
2) If not found, search in the protected hash.
3) If not found, search in the parent protected hash, and repeat step
- as necessary.
When symbol “@var” is first to be created (as lvalue), by default it is
stored in the protected hash. When “attr_private :@var” is encountered:
1) Search in the private hash.
2a) If found, do nothing.
2b) If not found, search in the protected hash.
3a) If found, move the symbol (key) and its value from the protected
hash to the private hash.
3b) If not found, create symbol “@var” and store it in the private
hash.
With this implementation, when “b = B.new” is executed, this is the state
of the class hashes:
class A: prot.keys = ['@a'] priv.keys = []
class B: prot.keys = [] priv.keys = []
Then later, when “attr_private :@a” is executed, this is the state of the
class hashes:
class A: prot.keys = ['@a'] priv.keys = []
class B: prot.keys = [] priv.keys = ['@a']
From now on, in class A, @a always refer to a protected variable, but in
class B, @a refers to a private variable, which is different from class
A’s @a (because of the search order above).
I know that Ruby internal implementation is currently not like this and
this new algorithm has some issue on efficiency. But in this discussion,
the question that we want to answer is whether we can or cannot use
“attr_private :@var”. (This is more theoretical than actual
implementation, so to speak.)
Regards,
Bill
···
==========================================================================
ts decoux@moulon.inra.fr wrote:
attr_private :@foo
It was proposed but you can’t use it. For example
class A
def initialize
@a = 12
end
end
class B < A; end
b = B.new
class B
attr_private :@a
end
When ruby execute attr_private, it has lost the information that the
instance variable @a was initialized in the class A
You must know at compile time, if an instance is class local.
Guy Decoux