Replace Temp with Query

Posted by student on Stack Overflow See other posts from Stack Overflow or by student
Published on 2008-11-26T14:48:51Z Indexed on 2010/03/16 0:29 UTC
Read the original article Hit count: 530

Filed under:

The Replace Temp with Query refactoring method is recommended quite widely now but seems to be very inefficient for very little gain.

The method from the Martin Fowler's site gives the following example:

Extract the expression into a method. Replace all references to the temp with the expression. The new method can then be used in other methods.

	double basePrice = _quantity * _itemPrice;
	if (basePrice > 1000)
		return basePrice * 0.95;
	else
		return basePrice * 0.98;

becomes

	if (basePrice() > 1000)
		return basePrice() * 0.95;
	else
		return basePrice() * 0.98;


double basePrice() {
	return _quantity * _itemPrice;
}

Why is this a good idea? surely it means the calculation is needlessly repeated and you have the overhead of calling a function. I know CPU cycles are cheap but throwing them away like this seems careless?

Am I missing something?

© Stack Overflow or respective owner

Related posts about refactoring