October 3, 2017
Manual Refactoring : Introduce Local Variable
In the second post in my series on manual refactoring, I'm going to cover another refactoring basic: Introduce Local Variable.
I can think of several use cases for this refactoring that come up regularly.
1. We might want to introduce a local variable so that we can explain the meaning of an expression by giving it a name. (e.g., memory.total() - memory.used() could become int availableMemory = memory.total() - memory.used() ).
2. We might not want to repeated a duplicated expression in our code, like the repeated call to combinations.size() in this code. Not only does it violate D.R.Y., but it does the same work twice to get an identical result.
3. We might want to move a reference out of a specific block of code to facilitate another refactoring, like Extract Method. But more about that in an upcoming post...
To illustrate Introduce Local Variable, I'm going to use the example code in #2.
First, I'm going to cut the whole expression.
Then replace it with the name of the variable I want to introduce.
Then I can declare the local variable and paste the original expression as the initial value.
NOW RUN THE TESTS!
And now that I have this local variable, I can eliminate the duplicated expression, which was my goal here.
AND RUN THE TESTS!
(I get an especially warm, fuzzy feeling because this particular project has more than 1,000 unit tests for < 400 lines of code. Especially when refactoring manually, favour high test assurance for extra safety.)
Posted 2 weeks, 5 days ago on October 3, 2017