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.

Tags: ,

Leave a Reply

You can use these tags in comments (Note: HTML is automatically escaped inside <pre> tags, nowhere else, so if you post source code, put it in <pre>):

<pre lang="some_programming_language"> 
<em>
<strong>
<a href="url">

NOTE: Comments are automatically spam-filtered. If your comment fails to appear, it was likely munched by the filter. Try not to link-spam or post anything that looks like it was typed by a robot.