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...
    bar
  end

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

  private

  attr_accessor :bar
end

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.set_bar("foo")
foo.get_bar #=> "foo"
Discover and read more posts from Michael Crismali
get started
Enjoy this post?

Leave a like and comment for Michael

1
1
1Reply
Abdullah Muhammad
5 months ago

What are your thoughts on using instance variables in controllers with frameworks like sinatra and rails. Their documentation encourages to use them. Can you please shed some light on it.

Get curated posts in your inbox

Read more posts to become a better developer