Introducing Ruby refactoring pattern called "Forward with Default Params." This applies to any language that supports parameter defaulting, actually. And, this pattern may already be documented somewhere for all I know - I haven't looked into it. If someone can point this out, I'll be happy to defer all credit. In the meantime...
Problem: You keep creating new methods, each calling the same helper or 'core' method (we'll call it 'method_a'), but with different params. You can't change the required params of the core method because spagetti-legacy code relies on method_a, without params, such as with Rails controllers. You should fix the spagetti code but time dictates otherwise. However, you feel dirty violating DRY in your controller. What to do?
# The Problem
def method_a
a = "Hello, "
b = "out there."
puts (a+b)
end
def method_b
# Duplicates method_a, except a and b are different
a = "It's turning into another "
b = "crazy day."
# Call puts (a+b), just like method_a
puts (a+b)
end
def method_c
a = "I will never again "
b = "code like this."
puts (a+b)
end
def method_c ... z # Keeps on violating DRY, criminal-like remorselessness
end
Solution: Make method_a accept parameters with each one defaulted to method_a's internal values.
This way the legacy code isn't broken. Then reduce all method_b ... z to call method_a with
parameters like the following:
# Forwarding with Default Params
def method_a(a = "Hello, ", b = "out there.")
puts (a+b)
end
def method_b
method_a("It's turning into another ", "crazy day.")
end
def method_b
method_a("I will never again ", "code like this.")
end
Comments