|
Gen-Extract Method |
Top Previous Next |
|
Minor apologies for the cute terminology, but I'll using Gen-Extract Method to refer to a "Generalized Extract Method" refactoring - it's just like a normal Extract Method, except that the extracted routine is made more generally applicable by getting some of it's information from parameters instead of constants, module-level variables, or other expressions. This might be something that you do quite a bit in Test-driven development scenarios - you write "the simplest code that could possibly work" in order to satisfy your current failing test. Then, once that works, you write another test case that "breaks" the code you just wrote. Usually, then you will go to the code you just wrote and generalize it, in a fashion resembling this, in order to handle a wider range of cases.
To take a somewhat absurd example, suppose you started with a routine like the following:
You want to generalize that 1 + 2 calculation. So you select the part highlit above, and click Extract Method. Then type the name "sum" for the new function, and check the box to make result the return value from a function, like this:
Now, this sum function is about as dumb as it gets - it computes the sum of two specific numbers, 1 and 2. But we can easily turn those numbers into parameters to the function, making it more general (though still dumb). To see how this is done, select the 1 in the selected text box and press the button marked ">"
Rename the new parameter x in the grid. Then do the same for the number 2 and variable name y. The result? A reusable function called sum, that takes two parameters. After you perform the refactoring, you might want to make Sum public, and/or move it to another module, if it's a generally-useful function (i.e., not this one).
|