Friday, August 25, 2006

Use Ruby Class Methods to Remove Duplication

One of my favorite features of Ruby is the ability to use class methods to remove duplication. When I'm developing if I find methods that are similar (or identical) I like to extract these methods and define them dynamically using class methods. I've previously written about Attribute Initializer, which was one of the first methods that I abstracted after noticing the duplication in the code base.

Another example pulled from an actual code base is the bubble method:
def bubble(*args)
args.each do |method_name|
define_method(method_name) do
self
end
end
end
The bubble method is used in our code base to facilitate a Domain Specific Language that reads like natural language. The bubble method was extracted from duplicate methods in the code base such as:
def flag
self
end

def as
self
end
However, the above defined bubble method allows the flag and as methods to be defined simply by using:
bubble :flag, :as
The current code base I'm working in has several of these class methods that do everything from simply returning self to creating entire object graphs.

The reduced code duplication is an obvious benefit to this style of programming. However, some developers dislike this style of programming because they feel that the class methods obscure intent and decrease readability. There is clearly a trade-off and in the end it may simply be a coding style choice.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.