lundi 16 novembre 2015

Passing parameters(arguments) inside an object - does it make sense?

(I believe this is not Ruby specific problem but if I'm wrong - let me know)

Having a given class:

class Car

  def initialize(steering_wheel, engine)
    @wheel = steering_wheel
    @engine = engine
  end

  def service!
    clean_steering_wheel and repair_engine
  end

  private 

  attr_reader :steering_wheel, :engine

  def clean_steering_wheel
    steering_wheel.do_stuff!
    # more stuff
  end

  def repair_engine
    engine.do_stuff!
    # more stuff
  end
end

I operate on fields (instance variables) by using getters inside private methods.

I could also change private methods to receive argument and let them operate on it:

class Car

  def initialize(steering_wheel, engine)
    @wheel = steering_wheel
    @engine = engine
  end

  def service!
    clean_steering_wheel(wheel) and repair_engine(engine)
  end

  private 

  attr_reader :steering_wheel, :engine

  def clean_steering_wheel(wheel)
    steering_wheel.do_stuff!
    # more stuff
  end

  def repair_engine(engine)
    engine.do_stuff!
    # more stuff
  end
end

Both solution will work and probably have no performance differences (arguments are references). Is there any difference between them? Something I overlooked? Which is the best practise?

Aucun commentaire:

Enregistrer un commentaire