On Wed, Dec 3, 2008 at 5:04 PM, Ron Fox <fox / nscl.msu.edu> wrote:
> Brian Candler wrote:
>>
>> Frank Tao wrote:
>>>
>>> # I have a class Adam
>>> # I want to modify the method("m_a") so that it will return the cached
>>> result
>>> # If no cached result is available, then return the original result
>>> # I want to create a class method(AKA: macro) to make it DRY
>>
>> You might want to look at the 'memoize' method in ActiveRecord trunk.
>>
>>> # So far, I have issues like
>>> # 1) dynmically define class variable
>>
>> I suggest: don't use a class variable :-) An instance variable of the
>> class would be fine. But personally I wouldn't keep the memoized values =
in
>> the class; I'd keep them in the instances themselves.
>>
> I suggest: don't make blanket statements like that ;-)
Correct, this should be thoroughly explained, well I will try ;)
> That depends on what he wants the cache to accomplish.  If the cache shou=
ld
> cache across all instances of Adam, a class variable is _exactly_ what he
> wants.  If it should only cache for the specific instance of Adam an
> instance variable is what he wants.
This might indeed be what he wants, but if it is he should be aware of
the implications that it has. It is against one of the most valued
principles of OO design, a class shall nothing know about its
subclasses (1). Now I agree that occasionally this principle shall be
violated for good reason. But I have not yet seen a use case for class
variables and IIRC not many have on this list. That is why by
instinct, and instinct can be wrong of course, many of us warn against
class variables, and sometimes without thorough explications.
>  If there will be many instances of Adam, and if Adam can peform operatio=
ns
> that invalidate cache then a global cache is so much easier to handle tha=
n
> one distributed over all instances of Adam...since two instances of adam =
may
> have the same item in their caches, and if instance one invalidates.. how=
 do
> you find/invalidate the item in instance 2?
And how would that be solved by class variables if I may ask?

(1) this is not necessarily easy to see, but assume this code and
please forgive me for shouting ;)
class Supa
  @@supa =3D :super
  def self.supa; @@supa end
end

p Supa.supa

class Dupa < Supa
  @@supa =3D :duper
  def self.supa; @@supa end
end

p Dupa.supa
p Supa.supa ### AND THAT REALLY HURTS

Cheers
Robert
--=20
Ne baisse jamais la t=EAte, tu ne verrais plus les =E9toiles.

Robert Dober ;)