Refactoring Parameterize Method
ProblemMultiple methods perform similar actions that are different only in their internal values, numbers or operations.
SolutionCombine these methods by using a parameter that will pass the necessary special value.
If you have similar methods, you probably have duplicate code, with all the consequences that this entails.
What's more, if you need to add yet another version of this functionality, you will have to create yet another method. Instead, you could simply run the existing method with a different parameter.
Sometimes this refactoring technique can be taken too far, resulting in a long and complicated common method instead of multiple simpler ones.
Also be careful when moving activation/deactivation of functionality to a parameter. This can eventually lead to creation of a large conditional operator that will need to be treated via Replace Parameter with Explicit Methods.
How to Refactor
Create a new method with a parameter and move it to the code that is the same for all classes, by applying Extract Method. Note that sometimes only a certain part of methods is actually the same. In this case, refactoring consists of extracting only the same part to a new method.
In the code of the new method, replace the special/differing value with a parameter.
For each old method, find the places where it is called, replacing these calls with calls to the new method that include a parameter. Then delete the old method.
Tired of reading?
No wonder, there are 7 hours worth of the text on this website.
Try out something different. We've just launched the interactive learning course on refactoring. It has more content and much more fun than a boring text.Learn more...
Everything is quite simple. This example is like video (but much cooler):
- After pressing the Play button, you will see floating messages, which will guide you through the example. You can proceed by clicking on them.
- You can fast-forward or return to previous steps by pressing arrow buttons on the left.
- Also, you can take a look at the code diff window, which will show what has changed in code during the example ()
- To check the code for errors, you can press "Compile and test" button ()