Refactoring Ruby: Extract Variable

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.

--

--

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