Avoid Instance Variables, Use Getters and Setters

Published Feb 09, 2015Last updated Feb 15, 2017

In Ruby, you can set and access instance variables like this:

@bar = "bar"
@bar #=> "bar"

But you shouldn't. You should always use getter and setter methods like so:

self.bar = "bar"
bar #=> "bar"

This is because instance variables never raise errors so this could happen to you:

@bar = "bar"
@barr #=> nil
# or...
@barr = "bar"
@bar #=> nil

With getters and setters you won't waste time tracking down bugs caused by spelling errors like the one above:

self.barr = "bar" #=> raises NoMethodError since `barr=`is not a method
barr #=> raises NoMethodError because `barr` is not a method

You don't even need to write the getters and setters yourself, you can just use attr_accessor (or attr_writer or attr_reader if you only want one or the other).

If you don't want to expose the getters or setters to the outside world then you can always make them private:

class Foo
  def get_bar
    # log something...

  def set_bar(value)
    # log something...
    self.bar = value


  attr_accessor :bar

foo = Foo.new

# These raise errors since we're calling private methods
foo.bar = "bar" #=> error!
foo.bar #=> error!

# But our public interface can still use these methods
foo.get_bar #=> "foo"
Discover and read more posts from Michael Crismali
get started