Should I use class variables or class-instance variables for class static variables in Ruby?

淺唱寂寞╮ 提交于 2020-02-02 11:29:34

问题


class Something
    @@variable = 'Class variable'

    def give_me
        @@variable
    end
end

class OtherThing
    @variable = 'Instance variable with an interface'

    class << self
        attr_accessor :variable
    end

    def give_me
        self.class.variable
    end
end

p Something.new.give_me
p OtherThing.new.give_me

What I want to know is, which one should I use? Which are the benefits and cons of each?

Class variables are:

  1. Private unless you make an interface
  2. Shared between inheritances
  3. Shorter to write

Class-instance variables are:

  1. Public, since you must use an interface to access them
  2. Not shared between inheritances, but are set to nil when inherited
  3. Longer to write

What else should I have in mind?


回答1:


I recently discovered ActiveSupport defines class_inheritable_accessor, which does what the class-instance variables do with the advantage that objects are not shared across inheritance, and you can have a default value for the variable when subclassing.

class Foo
  class_inheritable_accessor :x, :y
end

Foo.x = 1

class Bar < Foo
end

Bar.x #=> 1
Bar.x = 3
Bar.x #=> 3
Foo.x #=> 1

More info here

Just for completeness: of the two presented options, I prefer going with the class-instance variables, since is often the expected behavior.




回答2:


Never use class variables in Ruby, ever. They cause problems with inheritance. Always use class instance variables instead.




回答3:


You also have the option of declaring instance variables at the class level:

class Foo
    @bar = 'baz'

    def Foo.print
        puts @bar
    end
end

Overall, I'd avoid class variables, as the shared-across-inheritance model is often very surprising and non-obvious; to be honest, I'm not sure what utility they really offer, other than being a not-quite-global-global.

If you need a 'scoped' global variable, I'd go for class-level instance variables with accessors. You avoid the inheritance 'surprise', while still maintaining encapsulation.




回答4:


Class instance variables are generally more useful and less surprising than class variables, so you should probably use them.

And now I shall spell some things out in the excruciating detail you've come to expect from a Ruby answer on StackOverflow:

To declare or refer to a class instance variable, you need to be in class scope and use a single @ sign. This places the variable on the singleton class instance for that class.

Unfortunately, when you're in class scope and use the def keyword, your methods are placed on the list of instance methods for that class, and are executed in instance scope, so their @-sign variables will be on the instance they're in.

What we want instead is to define methods on the class, not on its instances. What that really means is that these methods are on the list of instance methods for the singleton class of the class object. (Phew!)

So, to sum up: There are at least four idioms for switching over and defining methods on the singleton class of the class object Foo:

class Foo
  @a, @b, @c, @d = 1, 2, 3, 4

  # 1. pass the target to def
  def Foo.a
    @a
  end

  # 2. pass the target to def, relying on the fact that self 
  # happens to be the class object right now
  def self.b
    @b
  end

  # switch from class scope to singleton class scope
  class << self

    # 3. define a plain accessor in singleton class scope
    def c
      @c
    end

    # 4. use a macro to define an accessor
    attr_reader :d
  end

end

p [Foo.a, Foo.b, Foo.c, Foo.d]
#=> [1, 2, 3, 4]

(There are probably half a dozen more ways to do this, once you factor in class_eval and define_method and the like, but that should satisfy you for now. :-))

One final note: class instance variables are only available via the class they're defined on. If you try to call any of those methods from (or via) a subclass, the methods will execute, but the @ variables will all be nil, since self will be the subclass's class object, not the parent class' class object.

class Bar < Foo
end

p [Bar.a, Bar.b, Bar.c, Bar.d]
#=> [nil, nil, nil, nil]


来源:https://stackoverflow.com/questions/7072269/should-i-use-class-variables-or-class-instance-variables-for-class-static-variab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!