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
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
fooas a parameter to a method, assigning to the parameter means to change
footo 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:
- Create a temp variable for the parameter
- Replace all references to the parameter, made after the assignment, to the temp variable
- Change the assignment to assign to the temp variable
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
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!