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)?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

the idea is ruby-agnostic. See stackoverflow.com/questions/3069901 for why properties should be favored over fields.
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 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.