Why are setter methods not used in initialization?

Viewed 1783

Recently I've been reading "Practical Object Oriented Design in Ruby", and I noticed one of the best practices was to use accessor methods instead of directly grabbing the @instance_variable. For example:

class Foo
  attr_accessor :bar

  def initialize(my_argument)
    @bar = my_argument
  end

  # bad
  # def lorem_ipsum
  #     @bar * 999
  # end

  # good
  def lorem_ipsum
    bar * 999
  end

end

It makes sense to keep things DRY, and, in case I need to process @bar somehow before actually grabbing its value. However, I noticed that the initialize method sets the value of the @bar instance variable directly:

class Foo
  attr_accessor :bar

  def initialize(my_argument)
    @bar = my_argument #<-- why isn't self.bar = my_argument used here?
  end

Is there a reason for this? Shouldn't the setter method be used instead of directly using the = operator to set the value of the instance variable?

4 Answers
Related