Replace Parameter with Method Call
You invoke a method, then pass the result as a parameter.
“The receiver can also invoke this method.”
Don’t pass what the receiver can get itself.
graph LR
A[Client gets X, calls Func(X)] -->|Refactoring| B[Client calls Func(), Func gets X]
When to apply (Smells)
- Long Parameter List: Passing data that the method could easily fetch.
Motivation
- Simplicity: Reduce the work the caller has to do.
Mechanics (Steps)
- In the method, call the other method directly.
- Remove the parameter.
Explanation
Problem
price = quantity * itemPrice; discount = getDiscount(price);
Solution
Inside getDiscount(): price = quantity * itemPrice; ...
Caller: discount = getDiscount();
Pros and Cons
| Pros | Cons |
|---|---|
Code example
Typescript
Before
After
PHP
Before
After