We prefer using attr_reader to instance variables

We at Bigbinary prefering using attr_readers, attr_writers, attr_accessors etc. instead of instance variables of the class wherever possible.

Consider the following examples

Approach #1

class Calculator
  def initialize(number)
    @number = number
  end
  def increment
    @number + 1
  end
  def decrement
    @number - 1
  end
end

Approach #2

class Calculator
  attr_reader :number
  def initialize(number)
    @number = number
  end
  def increment
    number + 1
  end
  def decrement
    number - 1
  end
end

While both the approaches give us desired results, we advocate Approach #2.

Reasons by which we support our opinion are as follows -

  • We feel directly accessing instance variable makes the code look dirty with less OO.

  • We also feel that having attr_reader for the variables supports more abstraction i.e., one can tell difference between two objects of a class by virtue of these simple attribute reader methods.