Hello and happy Monday!
Today I’m Reviewing…
Today I’m reviewing the Extract Method Refactoring pattern. If you’re new to refactoring like I am, you should consider purchasing Refactoring Ruby Edition.
What is Extract Method?
One example of using extract method is when upon glancing at a long method that we’ve written, we see that some of the code could be extracted out into a method of its own. This provides a benefit of the original method being easier to read, and may also lead to removing some duplication.
Heres an example from the book.
Here the author explains that we can pull out the two puts statements into its own method. We can then name this new method as an explanation of it’s purpose (what it’s doing).
And now our original method contains two methods with names that explain whats happening but hides the implementation details in the decomposed methods. Making
print_owing an easier read.
Variables vs No Local Variables
We’ve just seen an example where the parameter in our source method (
amount) wasn’t being altered. In those cases we can just pass the argument into our target method, and leave our source method parameter in tack as well.
Here’s an example from the book where we need to reassign a local variable.
If the variable is used after the code is extracted we need to make the extracted code return the altered value of the variable.
The book states that in the case above, the
outstanding local variable is being created with an initial value. So we only need to initialize it within the extracted method. If the variable involves something more than this, we would have to pass in the previous value as the parameter.
What if I Have More than One Variable to Return?
The book states that we can attempt to perform multiple extractions where each extraction is returning only one value. If this isn’t feasible, then the author suggests considering Replace Method with Method Object.
In closing, I’ve included an excerpt from the book which explains Replace Method with Method Object:
Use when: You have a long method that uses local variables in such a way that you cannot apply Extract Method.
How to use: Turn the method into its own object so that all the local variables become instance variables on that object. You can then decompose the method into other methods on the same object.
Applying Replace Method with Method Object turns all the local variables into attributes on the method object. You can then use Extract Method on this new object to create additional methods that break down the original method.
Extract Method is a common refactoring pattern. If the extraction improves viewing clarity, then we’re given the green light to implement this refactoring pattern. This is true even when our new name is longer than the code we’ve extracted.
I hope you’ve enjoyed my short reading experience into Refactoring patterns.