Project Ramon

A learning journey from a Ruby noob perspective

Ruby Refactoring: Remove Assignments to Parameters

Hello!

I hope that you all enjoyed your weekend.

Today I’ll be continuing my review of refactoring patterns from a book called Refactoring: Ruby Edition. Today’s review is of a pattern named Remove assignments to parameters.

Pass by Value in Ruby

I’m honestly still wrapping my mind around this, but I feel as though I’ve got the gist. Here is a snippet form this StackOverflow on the topic that I’ve found helpful to my understanding:

remove_assignment_to_parameters_img1

remove_assignment_to_parameters_img2

remove_assignment_to_parameters_img3

Remove Assignment to Parameters

In the book, the author makes a statement of clarity to what “assigns to parameter” means.

Here’s the excerpt:

If you pass an object named foo as a parameter to a method, assigning to the parameter means to change foo to refer to a different object.

The author isn’t opposed to modifications to the parameter being passed in, but he does object however to changing the parameter to refer to a completely different object.

There are two main areas of confusion that leads to his reasoning.

  • With pass by value, any change to the parameter isn’t reflected in the calling routine
  • It’s much clearer when we use only the parameter to represent whats been passed in, with consistency

Now we can get into the mechanics of this pattern:

  1. Create a temp variable for the parameter
  2. Replace all references to the parameter, made after the assignment, to the temp variable
  3. Change the assignment to assign to the temp variable
  4. Test

I think the example in the book very nicely illustrates the above step-by-step process:
Pre refactor example:

def discount(input_value, quantity, year_to_date)
  input_value -= 2 if input_value > 50
  input_value -= 1 if quantity > 100
  input_value -= 4 if year_to_date > 10000
  input_value
end

Post refactor example:

def discount(input_value, quantity, year_to_date)
  result = input_value
  result -= 2 if input_val > 50
  result -= 1 if quantity > 100
  result -= 4 if year_to_date > 10000
  result
end

Conclusion

In the book, the author goes into greater detail about pass by value in Ruby since its often a source of confusion. If you’ve been enjoying my brief reviews on the topic of refactoring in Ruby, why not head on over to Amazon and pick up your copy today!

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