0
Answered

Replace temp with query question?

Атанас Василев 3 years ago updated by MANISH MANGHWANI 4 months ago 3

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

+5
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 Атанас Василев 3 years ago
+5
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!

+3

I had the same query, and I understand now. 

I will further add to Alexander's well-explained answer. As he mentioned, 9/10 times we can use this refactoring strategy. I will add where not to apply this

1. If you have a database query operation involved 
2. if you are reading from a file
3. if anything involves with complexity greater than or equal to O(n^2)

Also, I think it is possible to calculate it once and store it as a class variable instead of a local variable.