4

Just curious what the best practice is for accessing an instance variable from within a class assuming attr_accessor is set.

class Test
  attr_accessor :user

  def initializer(user)
    @user = user
  end

  def foo
    @user
  end
end

or

class Test
  attr_accessor :user

  def initializer(user)
    @user = user
  end

  def foo
    self.user
  end
end

So by instance variable (@user) or getter method (Test#user)?

user577808
  • 2,317
  • 4
  • 21
  • 31

1 Answers1

7

Getter method, because it's easier to refactor. Say you want to update a time stamp at the point of access.

class Test
  def user
    @user.last_read = Time.now
    @user
  end
end

And all your references to user are updated with the new logic. Not so easy if your references are to @user.

Mori
  • 27,279
  • 10
  • 68
  • 73
  • 1
    the idea is ruby-agnostic. See http://stackoverflow.com/questions/3069901 for why properties should be favored over fields. – Gishu Jan 11 '12 at 05:14
  • What if the attr_accessor is only added for internal use? I don't need these attributes for external access, so at that point, is it unnecessary to add attr_accessor, and therefore makes more sense to just use the instance variable internally to get/set? – user577808 Jan 11 '12 at 12:20
  • 1
    @user577808 the same principle applies within a class, but the smaller the context, the less important it is, because refactoring is easier. However, it a good idea to expose a minimum interface of a class, so in this case if you use a get/set it should be private. – Mori Jan 11 '12 at 14:25