Project Ramon

A learning journey from a Ruby noob perspective

Ruby Refactoring: Replace Temp with Query Review

Hello and happy Wednesday!

Today I’ll be reviewing another refactoring pattern. This pattern is often an important step before using the Extract Method pattern.

 

Replace Temp with Query

This refactor pattern aims to rid us of temporary variables, often found in loops, by extracting the temporary variable into its own method. This has the benefit of allowing any method in our class to gain access to the data contained.

Here are the steps to performing this refactor:

  1. Extract the local variable’s value out into its own private method. You can alter the protection in the future later if need be
  2. Test that your code is still functioning as before the refactor
  3. Replace the local variable with this new method

An Example

def store_checkout
  total = (@price * @number_of_items)
  
  if total > 10.0
    total / 2
  else
   total * 1.5
  end
end

Ok, so we want to start out by taking the right hand assignment to the local variable total, and create a new private method for it.

Next we want to create a test that can validate for us that @price * @amount still performs exactly as before we extracted it out into it’s own private method.

I’ll add to a virtual unit test for this class:

describe '#total' do
  it 'returns the product of @price and @amount' do
    @price = 10.0
    @number_of_items = 5
    expect(class_name.total).to eq 50.0
  end
end

And finally we can remove the local variable code and the totals in store_checkout‘s loop will now be getting it’s value from the private method, since we’ve removed the local variable and its assigned statement.

def store_checkout
  if total > 10.0
    total / 2
  else
   total * 1.5
  end
end

private

def total
  @price * @number_of_items
end

In Closing

I’ve noticed that a lot of these refactor patterns work well together and in many cases must work together to effectively clean our code. As mentioned at the beginning of this post, Replace Temp with Query is no exception. In the future, as I become more familiar with these patterns, I think it would be fun and informative to try to find some random open source and apply several of these together in unison.

Have a productive remainder of your week!

Stay tuned…

Advertisements

Categories: Ruby

Tags: ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s