Refactoring Introduce Parameter Object
ProblemYour methods contain a repeating group of parameters.
SolutionReplace these parameters with an object.
Identical groups of parameters are often encountered in multiple methods. This causes code duplication of both the parameters themselves and of related operations. By consolidating parameters in a single class, you can also move the methods for handling this data there as well, freeing the other methods from this code.
More readable code. Instead of a hodgepodge of parameters, you see a single object with a comprehensible name.
Identical groups of parameters scattered here and there create their own kind of code duplication: while identical code is not being called, identical groups of parameters and arguments are constantly encountered.
- If you move only data to a new class and do not plan to move any behaviors or related operations there, this begins to smell of a Data Class.
How to Refactor
Create a new class that will represent your group of parameters. Make the class immutable.
In the method that you want to refactor, use Add Parameter, which is where your parameter object will be passed. In all method calls, pass the object created from old method parameters to this parameter.
Now start deleting old parameters from the method one by one, replacing them in the code with fields of the parameter object. Test the program after each parameter replacement.
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 ()