Refactoring Preserve Whole Object
ProblemYou get several values from an object and then pass them as parameters to a method.
SolutionInstead, try passing the whole object.
int low = daysTempRange.getLow(); int high = daysTempRange.getHigh(); boolean withinPlan = plan.withinRange(low, high);
boolean withinPlan = plan.withinRange(daysTempRange);
int low = daysTempRange.GetLow(); int high = daysTempRange.GetHigh(); bool withinPlan = plan.WithinRange(low, high);
bool withinPlan = plan.WithinRange(daysTempRange);
$low = $daysTempRange->getLow(); $high = $daysTempRange->getHigh(); $withinPlan = $plan->withinRange($low, $high);
$withinPlan = $plan->withinRange($daysTempRange);
low = daysTempRange.getLow() high = daysTempRange.getHigh() withinPlan = plan.withinRange(low, high)
withinPlan = plan.withinRange(daysTempRange)
The problem is that each time before your method is called, the methods of the future parameter object must be called. If these methods or the quantity of data obtained for the method are changed, you will need to carefully find a dozen such places in the program and implement these changes in each of them.
After you apply this refactoring technique, the code for getting all necessary data will be stored in one place – the method itself.
Instead of a hodgepodge of parameters, you see a single object with a comprehensible name.
If the method needs more data from an object, you will not need to rewrite all the places where the method is used – merely inside the method itself.
- Sometimes this transformation causes a method to become less flexible: previously the method could get data from many different sources but now, because of refactoring, we are limiting its use to only objects with a particular interface.
How to Refactor
Create a parameter in the method for the object from which you can get the necessary values.
Now start removing the old parameters from the method one by one, replacing them with calls to the relevant methods of the parameter object. Test the program after each replacement of a parameter.
Delete the getter code from the parameter object that had preceded the method call.
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 ()