)
例如代码中有个临时变量在函数上面某处表示长方形周长, 在函数下面被赋予面积, 也就是这个临时变量被赋值超过一次, 且表示的不是同一种量. 应该针对每次赋值, 分配一个独立的临时变量.一个变量只应表示一种量, 否则会令代码阅读者感到迷惑.冲动前:1234doubletemp (width height) * 2;//do somethingtemp width * height;//do something冲动后:1234doubleperimeter (width height) * 2;//do somethingdoublearea width * height;//do something7. Remove Assignments to Parameters (消除对参数的赋值操作)解释:传入参数分传值和传址两种, 如果是传址, 在函数中改变参数的值无可厚非, 因为我们就是想改变原来的值. 但如果是传值, 在代码中为参数赋值, 就会令人产生疑惑. 所以在函数中应该用一个临时变量代替这个参数, 然后对这个临时变量进行其它赋值操作.冲动前:123456publicdoubleFinalPrice(doubleprice,intnum){price price * num;//other calculation with pricereturnprice;}冲动后:123456publicdoubleFinalPrice(doubleprice,intnum){doublefinalPrice price * num;//other calculation with finalPricereturnfinalPrice;}8. Replace Method with Method Object (用函数物件代替函数)解释:冲动的写下一行行代码后, 突然发现这个函数变得非常大, 而且由于这个函数包含了很多局部变量, 使得无法使用Extract Method, 这时Replace Method with Method Object就起到了杀手锏的效果. 做法是将这个函数放入一个单独的物件中, 函数中的临时变量就变成了这个物件里的值域 (field).冲动前:1234567891011classBill{publicdoubleFinalPrice(){doubleprimaryPrice;doublesecondaryPrice;doubleteriaryPrice;//long computation...}}冲动后:123456789101112131415161718192021classBill{publicdoubleFinalPrice(){returnnewPriceCalculator(this).compute();}}classPriceCalculator{doubleprimaryPrice;doublesecondaryPrice;doubleteriaryPrice;publicPriceCalculator(Bill bill){//initial}publicdoublecompute(){//computation}}