This is a read-only archive!

Class instance variables

Previously I rambled about Ruby singleton classes. It turns out class instance variables are apparently actually recommended over class variables by many people. One big reason is that class variables are shared between classes and subclasses, which can lead to ugly behavior, but class instance variables are not. A google search leads to plenty of other people talking about this (example).

Today I saw on Ruby Forum some more discussion of class instance variables and it seems like a place for potential evil silent bugs. Look at this:

class A
    attr_reader :x
    def initialize
        @x = 1
    end
    def A.test
        @x = 2
    end
end

inst = A.new 
A.test
puts inst.x

This obviously prints "1", not "2". The reason is A.test operates in the context of the class, so you're really setting a A's class instance variable @x to 2, not the normal instance variable @x. But at a glance, in a program of significant size, I'm not sure how easy this would be to spot. I remember Java for example throws a fit if you try to access instance variables from inside a static method. Ruby silently allows it, which is a good thing in that it lets you do neat stuff with class instance variables, but it seems also like an easy way to create hard-to-identify bugs. I guess that argument applies to Ruby as a whole though.

May 02, 2007 @ 4:02 AM PDT
Cateogory: Programming
Tags: Ruby, Java