Refactoring Ruby: Extract Variable

Jon Lunsford
1 min readAug 20, 2018

--

Let’s take a look at a simple way to add clarity to your ruby methods. Extract Variable or Introduce Explaining Variable, it’s probably one of the least invasive refactoring methods. Don’t let the simplicity fool you though, any clarity or explicitness gained is well worth the change.

Use Extract Variable when you have complex expressions grouped together in a method. It’s better to describe your expressions as clearly, and IMO, as verbosely as needed.

Let’s use Extract Variable in the Movie#total_price method.

The bad version looks like:

def total_price
# BAD
price + (price * TAX_PERCENTAGE) - (price * (discount_percentage / 100.0))
end

While you can deduce that this method returns the total price of a movie, it takes too much effort to understand how it does so.

The good version looks like:

def total_price
# GOOD
tax = price * TAX_PERCENTAGE
discount = price * (discount_percentage / 100.0)
price + tax - discount
end

Now, at a glance we know the total price of a movie consists of price + tax — discount, and we now have clear, concise descriptions of those complex expressions.

--

--

Jon Lunsford

Engineer @convertkit, programming enthusiast, father, and musician