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

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

+5
source share
1 answer

As you can find in your documentation Class Variables :

Class variables are part of the global runtime state and, as such, facilitate the accidental or unintentional dependence of one part of the system on another part of the system. Thus, the system becomes more prone to problems in which something here is changing something. In particular, class variables can make it difficult to set up tests (because the context of the test includes the entire global state).

Essentially, this is a manifestation of a global state, which is almost universally considered evil , since it complicates testing and leads to a much more fragile class / structure of the program.

The stack overflow question can also be useful for reading, which shows the main problem with class variables: if any class inherits your class and modifies the class variable, each instance of this variable changes even from the parent! It’s clear that you can easily shoot yourself in the foot, so it’s better to avoid them if you are not very careful.

It is also worth comparing class variables with class instance variables. This question contains some good examples illustrating differences in usage, but essentially class variables are shared , while class instance variables are not common . Therefore, to avoid unwanted side effects, class instance variables are almost always what you want.

+7
source

Source: https://habr.com/ru/post/1260385/


All Articles