0
Answered

Replace temp with query question?

Atanas 6 months ago • updated by tod walker 2 months ago 2

Considering https://refactoring.guru/home/slides/long-method/7/

Why is it better to use function on every call for the sum?

What's wrong with:

double calculateTotal() {
  double basePrice = basePrice();
  if (basePrice > 1000) {
    return basePrice * 0.95;
  }
  else {
    return basePrice * 0.98;
  }
}
double basePrice() {
  return quantity * itemPrice;
}


Why call the basePrice() multiple times, when its value can be cached? 

Answer

+1
Answer
Answered

Hi, Atanas.


Great question! In most cases, this refactoring is mandatory as a step towards the Extract Method which is extremely common and useful. Replace Temp with Query can eliminate a local variable that stands in the way of extracting code into separate method.

As with other performance issues, let it slide for the moment. Nine times out of ten, it won't matter. When it does matter, you will fix the problem during optimization. With your code better factored, you will often find more powerful optimizations, which you would have missed without refactoring. If worse comes to worse, it's very easy to put the temp back.

GOOD, I'M SATISFIED
Satisfaction mark by Atanas 6 months ago
+1
Answer
Answered

Hi, Atanas.


Great question! In most cases, this refactoring is mandatory as a step towards the Extract Method which is extremely common and useful. Replace Temp with Query can eliminate a local variable that stands in the way of extracting code into separate method.

As with other performance issues, let it slide for the moment. Nine times out of ten, it won't matter. When it does matter, you will fix the problem during optimization. With your code better factored, you will often find more powerful optimizations, which you would have missed without refactoring. If worse comes to worse, it's very easy to put the temp back.

Hello, Alexander,
Thanks for the good explanation!