Refactoring long methods, a simple example in ruby

Aydar Omurbekov
1 min readJun 28, 2021

In this article, I would like to show how to refactor long methods in ruby.

Let’s say we have such a method with a long line hard to understand code.

def total 
amount + (amount * TAX) — (amount * (discount_percentage / 100.0)) +(amount * (tip_percentage / 100.0))
end

What is the best way to refactor this method?
I think you should start by breaking the long code into parts and come up with a variable name for each part.

def total
tax = amount * TAX
discount = amount * (discount_percentage / 100.0)
tip = amount * (tip_percentage / 100.0)
amount + tax — discount + tip
end

Looks much better than the original, doesn’t it?
Now let’s think about what we can improve further, we can now replace each variable with the query method.

Converting these variables to methods can greatly simplify this code and will also make them reusable.

def total 
amount + tax — discount + tip
end
def tax
amount * TAX
end
def discount
amount * (discount_percentage / 100.0)
end
def tip
amount * (tip_percentage / 100.0)
end

--

--