Saturday, December 16, 2006

Ruby: Use class methods to reduce duplication

Context: I had two method definitions in my class that were similar to the code below.
class TaxRemoteFacade

def state_tax
...
@remote.close
end

def federal_tax
...
@remote.close
end

end
I've only shown two, but we actually needed the @remote.close code at the end of several methods.

Solution: To reduce the duplication you could introduce a mixin with a method to remove the duplication.
module RemoteFacade
def remote_call(method_name, &block)
class_eval do
define_method name do
instance_eval &block
@remote.close
end
end
end
end
The TaxRemoteFacade can now be defined as the code below.
class TaxRemoteFacade
extend RemoteFacade

remote_call do :state_tax do
...
end

remote_call do :federal_tax do
...
end

end
Post a Comment