Refactoring Ruby: Replace Temp with Query

Jon Lunsford
1 min readAug 27, 2018

--

Let’s look at another simple yet powerful refactoring method, Replace Temp with Query. You can use this when you have a temporary variable holding the result of an expression. I will reach for this when temporary variables add too much to a method’s size/complexity, or when the result of an expression needs to be used in other methods.

Let’s use Replace Temp with Query in the Movie#total_price method.

The method before refactoring looks like:

def total_price
# Temp variables holding expressions
tax = price * TAX_PERCENTAGE
discount = price * (discount_percentage / 100.0)
price + tax - discount
end

The method after refactoring looks like:

def total_price
# Temp variables replaced with query methods
price + tax - discount
end

With the temp variables abstracted to private query methods, there’s even less to grok when understanding the role of total_price.

Let’s run through the exact steps to take when applying Replace Temp with Query:

  1. Extract the expression into a private method. Try to use a private method as we don’t want to change the public API of an object if we don’t have to.
  2. Replace all references to the temp with the method name. Additionally, use the new query methods in any other places that need them.

Reach for this when you need to share the result of an expression or to reduce the size/complexity of a method.

--

--

Jon Lunsford

Engineer @convertkit, programming enthusiast, father, and musician