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
The bad version looks like:
price + (price * TAX_PERCENTAGE) - (price * (discount_percentage / 100.0))
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:
tax = price * TAX_PERCENTAGE
discount = price * (discount_percentage / 100.0) price + tax - 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.