Dan Sharp
Dan Sharp

Reputation: 1279

Using ruby attr_readers inside a class (versus just using instance variables)?

I'm building a system that uses a lot of small classes to do data processing (each class does a different processing step, nice & SRP like). I initialize each class with some parameters then call an execute() method on the class, which then uses other private methods to do some of the data calculations.

My question is: if I'm not accessing any of the parameters outside of the class, should I just use the instance variables in the private methods? Or define an attr_reader?

For example, here's a bit of contrived code that I whipped up:

class Car
  attr_reader :make

  def initialize(make, model)
    @make = make
    @model = model
  end

  def execute
    apply_paint
    rotate_tires
  end

  private

  def apply_paint
    if make == "Toyota"
      Painter.paint(self, "red")
    else
      Painter.paint(self, "green")
    end
  end

  def rotate_tires
    if @model == "Sequoia"
      set_tire_size(:large)
    else
      set_tire_size(:normal)
    end
  end
end

So which is better? How I handled "make" or how I handled "model"?

If I know that I'm not using either of those variables outside of this class at all, should I just stick with instance variables? Or is it nicer to use the attr_reader because then I could convert them into actual methods without changing the rest of the code... i.e. since apply_paint uses make instead of @make, I could change make to be a local method if need be and not change the apply_paint method.

I keep waffling back-n-forth and can't figure out which is better. Maybe this is just a preference thing, but I wanted to see what thoughts others had on this issue.

Upvotes: 2

Views: 402

Answers (1)

baron816
baron816

Reputation: 701

Use attr_ methods. You can (and probably should) make them private if you're not accessing them outside of the class. Why use them? You improve readability by stating your intentions towards how it should be used. An attr_reader should be interpreted as "this variable should only be read".

Upvotes: 3

Related Questions