Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 behind this?

like image 992
Douglas Avatar asked Nov 26 '16 13:11

Douglas


People also ask

Why do we use class variables in Ruby?

Ruby Class Variables Class variables begin with @@ and must be initialized before they can be used in method definitions. Referencing an uninitialized class variable produces an error. Class variables are shared among descendants of the class or module in which the class variables are defined.

What is a class variable in Ruby?

Used declare variables within a class. There are two main types: class variables, which have the same value across all class instances (i.e. static variables), and instance variables, which have different values for each object instance.

What does variable mean in Ruby?

What is a variable? A variable is a name that Ruby associates with a particular object. For example: city = "Toronto" Here Ruby associates the string "Toronto" with the name (variable) city. Think of it as Ruby making two tables.

How do variables work in Ruby?

Variables in Ruby can contain different values and different types of values over time. The term variable comes from the fact that variables, unlike constants, can take different values over time. In the example, there is a variable called i . First it is assigned a value 5, later a different value 7.


1 Answers

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
like image 88
Purplejacket Avatar answered Oct 27 '22 00:10

Purplejacket