Codementor Events

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"
Michael Crismali
Discover and read more posts from Michael Crismali
get started
post comments1Reply
Abdullah Muhammad
8 years 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.

Find a Pair Programming Partner on Codementor

Find a Pair Programming Partner on Codementor

Want to improve your programming skills? Choose from 10,000+ mentors to pair program with.

Find a Pair Programming Partner on Codementor
By using Codementor, you agree to our Cookie Policy.