Refactoring Ruby: Extract Method

Extract Method can be used when you have several expressions, a code fragment, that can be grouped together. Even if there is one expression that could be better explained with a well thought out method name, it’s still a good move.

Let’s use Extract method on the Invoice#print method:

The method before refactoring looks like:

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

Often times, if you see comments explaining what a code fragment does, it’s a smell indicating there is a method to be extracted.

The method after refactoring looks like:

def print
print_branding
print_line_items
print_subtotal
end

Let’s walk through the steps used when applying Extract Method:

Reach for this when a method contains groups of seemingly un-related code fragments, or when better naming will make it easier for you or your coworkers to understand the intent of code.

--

--

Engineer @convertkit, programming enthusiast, father, and musician

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

Engineer @convertkit, programming enthusiast, father, and musician