Ruby Attr Antipattern

Recently I’ve seen a good handful of something that I’ve never seen before in the Ruby world, and it mystifies me. I’ve been going through exercises on Exercism (, and in the Ruby exercises I’ve seen several people using private attr_accessor. What?

The argument, so far, has been that it’s the same as doing it the long way so why not?

It’s weird. That’s why not. It’s not expressive. That’s why not. It’s a lazy shortcut that still didn’t buy you anything. That’s why not.

An example:

class Demo
  def initialize(something)
    @something = something

  def based_on_something
    something * 2

  attr_reader :something

So, I am all for the use of attr accessors, and I am all for tucking implementation details away in private methods. The use of a private attr does nothing for the latter. You’ve simply added more obscure code that doesn’t tell future you or future maintainers anything about what you intended or thought might happen. If you think the implementation might change or evolve, then go ahead and write the extra 2 lines to define the method explicitly. Otherwise just use the ivar.

Now, it’s entirely possible that I’m just being grumpy old man and shaking my cane. If there is a good reason that’s come along that I haven’t picked up on yet I would love to understand it. For now, though, I’m maintaining that this is a weird antipattern.


Filed under programming, ruby