Replace Temp with request

The Replace Temp method with the request refactoring method is highly recommended, but seems very inefficient for very little gain.

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

Extract expression into method. Replace all references to temp with an 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? Of course, this means that the calculation is unnecessarily repeated, and you have the overhead of calling the function. I know the processor cycles are cheap, but throw them away as if it seems careless?

Did I miss something?

+10
source share
8 answers

- , . - , , :

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

, , .

+6

, , , DRY !

temps ( , !) , , . ( ?) , - - . ( )

, - !:)

temp .

. temp . temps ( , ), () .

, , , ... ... ? !

temp, , 110% .

, -

- , / . , " " .

, temp () → SOLID!

+4

, , , . , , " temp " . , , , extract.

+3

. , . , 5% 2% , , . , , 6 - - , , .

  if (basePrice() > 1000)
     return bigTicketDiscount()
  else
     return regularDiscount()

double bigTicketDiscount(){
  return basePrice() * 0.95;
}

double regularDiscount(){
  return basePrice() * 0.98
}
+2

Reactoring Book - Replace Temp with Query, :

. , . , . , . , , . , .

+2

, - Extract Method .116.

: , Extract Method, .

, . , Replace Temp Query (120)....

, , . Inline Method Method with Method Object.

+2

, , , ; basePrice ( , ). , . " " , , -, , , (, , ( ). , , .

0

( , ) , . if basePrice(), . if .

, . , .

, , . . ( ) , ( , , - , .., ,… ). , , . , ( , , ).

What I usually do is that I code in queries most of the time, and when I see that I call a specific request several times (unlike this example, where it is in separate conditional branches), I can use temp if it is local or introduces a memo or other type of caching system (such as a simple global variable or class member), if I need access to it in a wider, less local area.

When the reverse refactoring "Replace the request with Temp" comes in handy.

0
source

All Articles