Avoid Instance Variables, Use Getters and Setters
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"
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.