Refactor ComposingMethods inlineTemp

Refactor-ComposingMethods:inlineTemp

在重構的Composing methods中,有許多重構方法。這篇將介紹inline Temp的使用方法。

Problem & Solution

1
2
Problem:You have a temporary variable that’s assigned the result of a simple expression and nothing more.
Solution:Replace the references to the variable with the expression itself.

Example by Java before Rafactor

1
2
3
4
boolean hasDiscount(Order order) {
double basePrice = order.basePrice();
return basePrice > 1000;
}

Example by Java after Rafactor

1
2
3
boolean hasDiscount(Order order) {
return order.basePrice() > 1000;
}

Why Refactor

1
Inline local variables are almost always used as part of Replace Temp with Query or to pave the way for Extract Method.

Benefits

1
2
This refactoring technique offers almost no benefit in and of itself. However, if the variable is assigned the result of a method,
you can marginally improve the readability of the program by getting rid of the unnecessary variable.

Drawbacks

1
2
Sometimes seemingly useless temps are used to cache the result of an expensive operation that’s reused several times. 
So before using this refactoring technique, make sure that simplicity won’t come at the cost of performance.

How to Refactor

1
2
3
Find all places that use the variable. Instead of the variable, use the expression that had been assigned to it.

Delete the declaration of the variable and its assignment line.