Refactoring Ruby: Extract Method

def print
print_branding
# print line items
line_items.each do |line_item|
puts "#{line_item.name}: #{line_item.price}"
end
# print subtotal
puts "Subtotal: #{line_items.sum(&:price)}"
end
def print
print_branding
print_line_items
print_subtotal
end
  1. Identify candidate fragments by looking for some common smells like, expressions that cluster together, comments explaining the intent, or if a good method name could add clarity.
  2. Turn those fragments into a method whose name explains the purpose of the method.

--

--

Engineer @convertkit, programming enthusiast, father, and musician

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jon Lunsford

Jon Lunsford

Engineer @convertkit, programming enthusiast, father, and musician