Replace Parameter with Explicit Methods
A method runs different code depending on the value of an enumerated parameter.
“You have a method that runs different code depending on the values of an enumerated parameter.”
Make it specific.
graph LR
A[setValue(name, val)] -->|Refactoring| B[setName(val)]
When to apply (Smells)
- Switch Statements: Method body assumes behavior based on a flag.
Motivation
- Clarity:
turnOn()is clearer thansetSwitch(ON).
Mechanics (Steps)
- Create a method for each value of the parameter.
- Move the corresponding logic to the new methods.
- Remove the old method.
Explanation
Problem
setValue("height", 10)
Solution
setHeight(10)
Pros and Cons
| Pros | Cons |
|---|---|
Comparison
- Inverse Refactoring: Parameterize Method.
Code example
Typescript
Before
After
PHP
Before
After