Explaining the variable pattern

Ruby on Rails / Refactoring

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.