mardi 3 mars 2015

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

Foo.new.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!


Aucun commentaire:

Enregistrer un commentaire