Early return — my favourite quick refactor
1 min readJul 27, 2020
TL:DR when you see if/elses see if its possible to use early returns.
Code samples are in Ruby.
Here’s an example of some code I found in our User model recently.
def cancel_account
if cancellable?
update(status: "cancelled", cancelled_at: Time.zone.now)
else
false
end
end
This looks fine but, if we use early return we can make it
def cancel_account
if !cancellable?
return false
end
update(status: "cancelled", cancelled_at: Time.zone.now)
end
I would not say the original code for cancel_account
was complex or too difficult to understand. However, the new version I find a lot easier to read and understand.
Adding the cancellable?
check to the start works like a guard clause. That is we have all the things that would stop this method completing its actions right at the top.
Also because ruby is so pleasant we can remove the if end and do a one-liner instead so we end up with
def cancel_account
return false if !cancellable?
update(status: "cancelled", cancelled_at: Time.zone.now)
end