Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Why instantiate an object and use an instance method when a class method would suffice?

I am trying to learn design patterns by reading code that has been written by other people. Recently I've been focusing on the difference between class methods and instance methods.

In some code I was reading, I came across the following use of an instance method:

class Foo
  def bar!(baz)
    # do something to baz
  end
end

my_foo = Foo.new
my_foo.bar!(baz)

Why use an instance method here? The Foo class only exists to do bar, so why not just use a class method? From what I've been learning, my inclination would've been do to this:

class Foo
  def self.bar!(baz)
    # do something to baz
  end
end

Foo.bar!(baz)

Is there any reason to go with the first pattern? Is it just a matter of preference? My thought was that making an object uses memory and so the first one is actually inefficient, but am looking for any advice from more experienced folks. Thanks!

like image 743
sixty4bit Avatar asked Mar 17 '23 20:03

sixty4bit


1 Answers

There is no reason to prefer the former over the latter. Instantiating a class could cause a slight performance hit due to the GC doing more work, but I think you should really be asking yourself this question:

Is there ever any reason to create multiple instances of the class?

I.e. could you just do foo = Foo.new and then use foo everywhere? If so, you don't need a class at all. In fact, a similar argument applies to your second example. While it is an improvement over the first, there is still no reason to create instances of the class. So don't use a class, use a module.

module Foo
  def self.bar(baz)
  end
end
like image 181
Max Avatar answered Apr 08 '23 08:04

Max