Using private attr_accessors is wrong
I’m working on an existing Rails application and there’s one pattern I see repeating often that I’m puzzled with. It’s especially common in service objects. Here’s couple of reasons you should not use private attr_accessors.
Comments
While I agree it’s in general bad to use a private
attr_accessor
(because of the issues you’ve outline in your blog post), I really dig the usage of a privateattr_reader
. IMHO it makes the code easier to read (because it’s not cluttered with @’s) and easier to change - say you no longer set your @thing to one of the arguments during initialization, but you need something more complex. Super easy to change with anattr_reader
, because you can simply replace it with a method.I suggest Sandi Metz’s “Practical Object-Oriented Design In Ruby” book (“Hide Instance Variables” in Chapter 2).
I use “protected” attr_accessors Very useful for catching careless typo
Instance variables are not very cool to use because a simple typo in it’s name results into Ruby silently returning nil instead of raising an exception. That’s why in our codebase ivars are only allowed in initializers.
Post a comment