I have been doing a lot of about convience methods in Ruby lately. I have, noticed others that over use the convience of creating a class with instance level methods and wrapping all of it in a class level method for convience. (this is not new to me - just to be clear. Rather something I am reflecting on)
consider:
class FunkyBusiness
attr_reader :initial_state
def initialize(initial_state)
@initial_state = initial_state
end
def state_mutator
# do something to, or produce something from initial_state
end
end
with the usage of:
FunkyBusiness.new(123).state_mutator # => something awesome
Seems like a pretty straight forward implementation of a class right? I mean, by definition we are saying I give FunkyBusiness something in it gives me something out.
Now consider:
class FunkyBusiness
attr_reader :initial_state
def self.state_mutator(initial_state)
new(initial_state).state_mutator
end
def initialize(initial_state)
@initial_state = initial_state
end
def state_mutator
# do something to, or produce something from initial_state
end
end
with the usage of:
FunkyBusiness.new(123).state_mutator # => something awesome
or
FunkyBusiness.state_mutator(123) # => something awesome
This is all done in favor of removing the new
keyword in the name of a better interface. Well this is where I start to question if infact it is a better interface. There are a couple reasons. Probably the most important one to me is littering the class with duplication just for convience. Now that being said it could reduce lines of code elsewhere in the system, but I be willing to bet that there are other problems if that is the case. Two if state is important! make sure it is seen as important. When creating convience methods like this we are hiding the fact that the class holds onto state inside the class method.
Like anything there is no golden rule for right or wrong with this pattern, all I am trying to do is raise the question. I'd love to hear some feedback on what you think!