5.introduce explaining variable if you have a complicated expression,put the result of the expression, or parts of the expression , in a temporary variable with a name that explains the purpose. introduce explaining variable is particulaly valuable with conditional logic in which it is useful to take each clause of a condition and explain what the condition means a well-named temp. another case is a long algorithm,in which each step in the computation can be explained with a temp.mechanics (1)declare a final temporary variable,and set it to the result of part of the complex expression. (2)replace the result part of the expression with the value of the temp.before:double price(){ return quantity*itemprice-math.max(0,quantity-500)*itemprice*0.05+math.min(quantity*itemprice*0.1,100.0);}after:double price(){ final double baseprice= quantity*itemprice; final double quantitydiscount=math.max(0,quantity-500)*itemprice*0.05 ; final double shipping=math.min(quantity*itemprice*0.1,100.0); return baseprice-quantitydiscount+shipping;}
... 下一页