October 8, 2017
Manual Refactoring : Inlining Complex Methods
Yesterday I posted about manually inlining variables and methods with a couple of simple examples. But inlining methods in particular is not always that straightforward, so today let's consider a beefier example.
What about inlining methods that contain more than a single expression? And what if any parameter values being passed in aren't local variables in the calling code, but more complex expressions themselves?
Well, actually, that's still pretty straightforward. Consider this example:
I want to inline the method calculate_price(). Again, the first step is to replace references to parameter names inside that method with the parameter values being passed in.
NOW RUN THE TESTS!
Then we can paste the code inside that method in place of the call to it.
AND RUN THE TESTS!
And then finally - because calculate_price() is no longer being used - we can delete the method.
DON'T FORGET TO RUN THE TESTS!!
Now let's think about situations where a method might be called in multiple places. How would we inline that?
Frankly, I probably wouldn't. If a method's being called in multiple places, that suggests that inlining it would introduce duplication. So, for me, a precondition to inlining methods is that they're only called in one place.
But if you absolutely must, then the only real variation in the process would be that you might need to match up the parameter values multiple times, if each caller is calling them something different.
Posted 3 years, 2 months ago on October 8, 2017