Refactoring Replace Parameter with Method Call

Problem

Calling a query method and passing its results as the parameters of another method, while that method could call the query directly.

Solution

Instead of passing the value through a parameter, try placing a query call inside the method body.

Before
int basePrice = quantity * itemPrice;
double seasonDiscount = this.getSeasonalDiscount();
double fees = this.getFees();
double finalPrice = discountedPrice(basePrice, seasonDiscount, fees);
After
int basePrice = quantity * itemPrice;
double finalPrice = discountedPrice(basePrice);
Before
int basePrice = quantity * itemPrice;
double seasonDiscount = this.GetSeasonalDiscount();
double fees = this.GetFees();
double finalPrice = DiscountedPrice(basePrice, seasonDiscount, fees);
After
int basePrice = quantity * itemPrice;
double finalPrice = DiscountedPrice(basePrice);
Before
$basePrice = $this->quantity * $this->itemPrice;
$seasonDiscount = $this->getSeasonalDiscount();
$fees = $this->getFees();
$finalPrice = $this->discountedPrice($basePrice, $seasonDiscount, $fees);
After
$basePrice = $this->quantity * $this->itemPrice;
$finalPrice = $this->discountedPrice($basePrice);
Before
basePrice = quantity * itemPrice
seasonalDiscount = this.getSeasonalDiscount()
fees = this.getFees()
finalPrice = discountedPrice(basePrice, seasonalDiscount, fees)
After
basePrice = quantity * itemPrice
finalPrice = discountedPrice(basePrice)

Why Refactor

A long list of parameters is hard to understand. In addition, calls to such methods often resemble a series of cascades, with winding and exhilarating value calculations that are hard to navigate yet have to be passed to the method. So if a parameter value can be calculated with the help of a method, do this inside the method itself and get rid of the parameter.

Benefits

  • We get rid of unneeded parameters and simplify method calls. Such parameters are often created not for the project as it is now, but with an eye for future needs that may never come.

Drawbacks

  • You may need the parameter tomorrow for other needs... making you rewrite the method.

How to Refactor

  1. Make sure that the value-getting code does not use parameters from the current method, since they will be unavailable from inside another method. If so, moving the code is not possible.
  2. If the relevant code is more complicated than a single method or function call, use Extract Method to isolate this code in a new method and make the call simple.
  3. In the code of the main method, replace all references to the parameter being replaced with calls to the method that gets the value.
  4. Use Remove Parameter to eliminate the now-unused parameter.

Tired of reading?

No wonder, there are 7 hours worth of the text on this website.

Try our interactive course on refactoring. It offers less boring approach to learning new stuff.

Let's see...