Private Attribute Accessor in Ruby is An Artifact from Other Languages

Prem Sichanugrist
Sikachu's Blog
Published in
2 min readJun 4, 2018

--

I’ve recently started seeing a trend of defining a private attr_accessor in Ruby code, and I honestly seeing them as an artifact from other programming languages. It’s something that followed the developer after they switched to use Ruby.

Back in the day when I studied object-oriented programming using Java, I was taught to define a private getter and setter for the class. After all, it make sense in a very strict-typed language such as Java, as you might need to overload setters to type-cast for each type of the argument you expected.

However, since Ruby is not strongly typed, and method overloading isn’t really a thing in Ruby, I don’t think it’s necessary to have a private attr_accessor.

Consider this simple example:

class Person
def initialize(name)
self.name = name
end
private attr_accessor :name
end

There is no difference between the above example and this below example which just use an instance variable:

class Person
def initialize(name)
@name = name
end
end

Don’t you think that the second version also looks more clean and concise?

I believe it’s time to stop this private attr_accessor trend, and just access instance variable within the class the way they are intended to be.

  1. I think if you need to have a logic to cast or convert value, it’s okay to actually define a private setter. By stop using a simple setter altogether, you are actually going to save yourself from having to check your code if the setter is actually a simple one or has additional logic to it. If you see an instance variable assignment, you will know right away that it’s a simple assignment!
  2. I know that you can do private attr_accessor :name in Ruby nowadays. However, it’s highly likely that you will have other private methods in this class, which you will usually switch to a begin-here declaration type.

--

--

Senior Developer at Degica. I also contribute to open source projects, mostly in Ruby.