Inline Method (内联函数)
Before
int getRating() {
return (moreThanFive()) ? 2: 1;
}
boolean moreThanFive() {
return NUMBER > 5;
}
After
int getRating() {
return NUMBER > 5 ? 2 : 1;
}
Inline Temp (内部临时变量)
Before
double basePrice = getBasePrice();
return (basePrice > 1000);
After
return getBasePrice() > 1000;
Replace Temp with Query (以查询取代临时变量)
Before
double getPrice(){
int basePrice = quantity * itemPrice;
double discountFactor;
if (basePrice > 1000) discountFactor = 0.95;
else discountFactor = 0.98
return basePrice * discountFactor;
}
After
double getPrice(){
return getBasePrice() * getDiscountFactor();
}
private int getBasePrice(){
return quantity * itemPrice;
}
private double getDiscountFactor () {
return getBasePrice() > 1000 ? 0.95 : 0.98;
}