Skip to content

Instantly share code, notes, and snippets.

@jwilger
Last active October 10, 2017 21:06
Show Gist options
  • Save jwilger/4ab26e333f9c3fd7c8dadd9ce000f24d to your computer and use it in GitHub Desktop.
Save jwilger/4ab26e333f9c3fd7c8dadd9ce000f24d to your computer and use it in GitHub Desktop.
Why I Avoid Instance Variables in Ruby

In general, I try to avoid using instance variables directly in Ruby. Using private accessor methods wherever possible accomplishes two things:

  1. It makes it much easier to refactor down the line if you end up needing to add some additional behavior whenever a value is set (validation, callbacks, etc), because you need only add the #my_attr= method definition and need not find all the places where you used @my_attr = ... and change them as well.

  2. It better guards against the kind of typo-induced bugs that leave one staring at their computer for half an hour cursing the day they decided to earn a living as a programmer. For example:

class Foo
attr_reader :bar1
def initialize(bar)
@barl = bar
end
end
f = Foo.new('baz')
# ...
# Some significant separation of both space and time in the execution of code...
# ...
f.bar1
#=> nil
# developer chucks laptop at wall
class Foo
attr_accessor :bar1
private :bar1=
def initialize(bar)
self.barl = bar
end
end
f = Foo.new('baz')
# NoMethodError exception raised that clearly points out
# the source of the error right away
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment