Refactoring: Refactorings/Remove Named Parameter
Jump to navigation
Jump to search
Logically the inverse of Introduce Named Parameter: The fluency that named parameters bring is no longer worth the complexity on the receiver. Converts the named parameter list back into a standard parameter list
Mechanics
- Choose the parameter to remove from named parameter Hash. In receiving method, replace named parameter with a standard parameter (before the Hash, if there still is one).
- Replace named parameter in calling code with a standard parameter
- Test
Example
Before
class Books
def self.find(hash={})
hash[:joins] ||= []
hash[:conditions] ||= ""
sql = ["SELECT * FROM books"]
hash[:joins].each do |join_table|
sql << "LEFT OUTER JOIN #{join_table} ON"
sql << "books.#{join_table.to_s.chap}_id"
sql << " = #{join_table}.id"
end
sql << "WHERE #{hash[:conditions]}" unless hash[:conditions].empty?
sql << "LIMIT 1" if hash[:selector] == :first # oops, we want selector to be a required parameter...
connection.find(sql.join(" "))
end
end
After
class Books
def self.find(selector, hash={})
hash[:joins] ||= []
hash[:conditions] ||= ""
sql = ["SELECT * FROM books"]
hash[:joins].each do |join_table|
sql << "LEFT OUTER JOIN #{join_table} ON"
sql << "books.#{join_table.to_s.chap}_id"
sql << " = #{join_table}.id"
end
sql << "WHERE #{hash[:conditions]}" unless hash[:conditions].empty?
sql << "LIMIT 1" if selector == :first
connection.find(sql.join(" "))
end
end