This question was put on hold for being off-topic:
https://codereview.stackexchange.com/questions/58091/why-is-it-suggested-to-replace-temp-with-query
To refactor the code, it is suggested here to replace Temp with Query, for example in following code, basePrice should be extracted to a method. I am wondering why is it a good practice? If I keep the temporary variable the equation will be calculated once rather than three times.
double basePrice = _quantity * _itemPrice; if(basePrice > 1000) return basePrice * 0.95; else return basePrice * 0.98;
Convert to
if(basePrice() > 1000) return basePrice() * 0.95; else return basePrice() * 0.98; .... double basePrice(){ return _quantity * _itemPrice; }
This was closed on the grounds of:
"Questions must involve real code that you own or maintain. Questions seeking an explanation of someone else's code are off-topic. Pseudocode, hypothetical code, or stub code should be replaced by a concrete example."
I think the question is different from the "someone else's code", or "hypothetical code" categories. It's about a not-so-clear-cut practice recommended by a book, and something that can easily come up during a code review session in real life, in real projects, where I'll have to take a stand and accept or reject the proposed change. It will be nice to have a public discussion on this and find out what our community recommends.
The question falls well within the two top items in the "Purpose of a Code Review" of this related post:
- Conformity and maintainability - does the code conform to the standards and expectations of your peers... [...]
- Performance and efficiency - are there ways to make the code go faster, or do what its doing more efficiently
So the question is, do you still think it's off topic? If not then let's reopen, and let's take a stand.
UPDATE
This kind of question could be labeled as "refactoring technique". It's a practical issue that can easily come up in real life code review, and it deserves an answer.