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. However, don’t let the simplicity fool you; any clarity or explicitness gained is well worth the change.
When you have complex expressions grouped together in a method, it's best to describe them as clearly and verbosely as necessary using the Extract Variable technique. Let's apply this approach to the Movie#total_price
method in the code example below:
class Movie
TAX_PERCENTAGE = 0.5
def initialize(price:, discount_percentage: 0)
@price = price
@discount_percentage = discount_percentage
end
def total_price
# BAD
price + (price * TAX_PERCENTAGE) - (price * (discount_percentage / 100.0))
end
private
attr_reader :price, :discount_percentage
end
class Movie
TAX_PERCENTAGE = 0.5
def initialize(price:, discount_percentage: 0)
@price = price
@discount_percentage = discount_percentage
end
def total_price
# GOOD
tax = price * TAX_PERCENTAGE
discount = price * (discount_percentage / 100.0)
price + tax - discount
end
private
attr_reader :price, :discount_percentage
end
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.
To improve this method, we'll apply the Extract Variable pattern:
def total_price
# GOOD
tax = price * TAX_PERCENTAGE
discount = price * (discount_percentage / 100.0)
price + tax - discount
end
In the improved "good" version, we introduce two explaining variables: tax
and discount
.
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.
By applying the Extract Variable refactoring pattern, we've made the code more readable and understandable, enhancing its overall clarity.
Top comments (4)
And to take it all the way ...
Great point! Yep, a fantastic next step is to use the Extract Method ... method :)
It's interesting how these tiny adjustments can dramatically improve clarity in your code.
Simple and direct to the goal! excelent article
Thanks very much!