Refactoring Ruby on Rails

Ruby on Rails / Refactoring – explaining variable pattern

Ruby on Rails / Refactoring – explaining variable pattern January 24, 20182 Comments

Explaining variable refactoring, as its name is pointing, depends on moving logic of a complicated expression to temporary variables with meaningful names.

Refactoring code this way makes it more readable, more simple and more explainable. To better demonstrate the idea behind this way of refactoring let’s assume that we have some complicated if condition:

if(user.sign_in_count > 0 && user.posts.any? && (company.employees.size > 100 || company.mode == :maintenance)
  # do some stuff
end

You need to focus a little bit to understand all of the conditions used here. We can simplify it by moving each condition to the variable which name would explain what’s happened:

user_signed_in = user.sign_in_count > 0
user_has_posts = user.posts.any?
large_company = company.employees.size > 100
company_in_maintenance = company.mode == :maintenance

if(user_signed_in && user_has_posts && (large_company || company_in_maintenance)
  # do some stuff
end

You can also move logic to separated methods. Now the code is more readable and self-explainable, isn’t it? We don’t have to wonder what author mean by using this condition.

Have problems with refactoring of your Ruby on Rails application?

Hit me on twitter or use contact form and let me know how can I help you!

Image source: Photo by Kaboompics // Karolina from Pexels https://www.pexels.com/photo/behind-of-woman-gesturing-6385/

Download free RSpec & TDD ebook

Do you want to earn more or jump to the next level in your company? Do you know that testing skills are one of the most desired skills? There is only first step: start testing and do it right. My ebook can help you. Subscribe to the newsletter to get a free copy of the book.

2 comments

  1. It is called “Extract variable” pattern, and “explaining variable pattern” is a bit confusing sentence in English and not what you meant, and at last – you’re missing one bracket at the end 😉

Leave a Reply

Your email address will not be published. Required fields are marked *