Why is using a class variable in Ruby considered a 'code smell'?

[亡魂溺海] 提交于 2019-12-10 02:46:50

问题


According to Reek, creating a class variable is considered a 'code smell'. What is the explanation behind this?


回答1:


As you can find in their documentation on Class Variables:

Class variables form part of the global runtime state, and as such make it easy for one part of the system to accidentally or inadvertently depend on another part of the system. So the system becomes more prone to problems where changing something over here breaks something over there. In particular, class variables can make it hard to set up tests (because the context of the test includes all global state).

Essentially, it's a manifestation of global state, which is almost universally considered evil, because it makes tests more difficult and results in a much more fragile class/program structure.

This Stack Overflow question may also be worth reading, which shows the main problem with class variables: if any class inherits from your class and modifies the class variable, every instance of that variable changes, even from the parent! This understandably gives you a way to shoot yourself in the foot easily, so it may be best to avoid them unless you're very careful.

It's also worth comparing class variables with class instance variables. This question has a few good examples which illustrate the usage differences, but in essence class variables are shared, whereas class instance variables are not shared. Therefore, to avoid unwanted side effects, class instance variables are almost always what you want.




回答2:


In brief, this:

class Shape
  @@sides = 0

  def self.sides
    @@sides
  end
end

class Pentagon < Shape
  @@sides = 5
end

puts Shape.sides  # oops ... prints 5


来源:https://stackoverflow.com/questions/40819068/why-is-using-a-class-variable-in-ruby-considered-a-code-smell

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