java 代码细节(inline temp)

来源:互联网 发布:石家大唐数据招聘 编辑:程序博客网 时间:2024/04/30 04:23



这个观点来自《重构-----改善既有代码的设计》

You have a temp that is assigned to once with a simple expression, and the temp is getting in the way of other refactorings.

02

Replace all references to that temp with the expression.

03
       double basePrice = anOrder.basePrice();       return (basePrice > 1000)    
graphics/arrow.gif
04
       return (anOrder.basePrice() > 1000)

Motivation

05

Most of the time Inline Temp is used as part of Replace Temp with Query, so the real motivation is there. The only time Inline Temp is used on its own is when you find a temp that is assigned the value of a method call. Often this temp isn’t doing any harm and you can safely leave it there. If the temp is getting in the way of other refactorings, such as Extract Method, it’s time to inline it.

Mechanics

06
  • Declare the temp as final if it isn’t already, and compile.

    This checks that the temp is really only assigned to once.
  • Find all references to the temp and replace them with the right-hand side of the assignment.

  • Compile and test after each change.

  • Remove the declaration and the assignment of the temp.

  • Compile and test.