Replace Parameter with Explicit Methods.
Problem
A method is split into parts, each of which is run depending on the value of a parameter.
Solution
Extract the individual parts of the method into their own methods and call them instead of the original method.
##Example
Before
void setValue(String name, int value) {
if (name.equals("height")) {
height = value;
return;
}
if (name.equals("width")) {
width = value;
return;
}
Assert.shouldNeverReachHere();
}After
void setHeight(int arg) {
height = arg;
}
void setWidth(int arg) {
width = arg;
}##Why Refactor
A method containing parameter-dependent variants has grown massive. Non-trivial code is run in each branch and new variants are added very rarely.
##Benefits
- Improves code readability. It’s much easier to understand the purpose of
startEngine()thansetValue("engineEnabled", true).
##How to Refactor
-
For each variant of the method, create a separate method. Run these methods based on the value of a parameter in the main method.
-
Find all places where the original method is called. In these places, place a call for one of the new parameter-dependent variants.
-
When no calls to the original method remain, delete it.