Replace Temp with Query 以查询取代临时变量的方法只适用于处理某些类型的临时变量,即那些只被赋值一次,而且之后再也没有被修改的临时变量。 看下面的代码:我们可以将 price()
中的临时变量 basePrice
和discountFactor
替换为查询函数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 class Order { constructor (quantity, item ) { this .quantity = quantity; this .item = item; } get price () { const basePrice = this .quantity * this .item .price ; let discountFactor = 0.98 ; if (basePrice > 1000 ) { discountFactor -= 0.03 ; } return basePrice * discountFactor; } }
修改后如下:可以看到,修改后,price()
内的代码明显更加简洁,更加容易理解。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 constructor (quantity, item ) { this .quantity = quantity; this .item = item; } get price () { return this .basePrice * this .discountFactor ; } get basePrice () { return this .quantity * this .item .price ; } get discountFactor () { let discountFactor = 0.98 ; if (this .basePrice > 1000 ) { discountFactor -= 0.03 ; } return discountFactor; }
最后,discountFactor()
函数还可以进一步简化:
1 2 3 get discountFactor () { return this .basePrice > 1000 ? 0.95 : 0.98 ; }
如果是在不支持getter
和setter
的语言中,我们可以使用extract function
的方法来实现。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 constructor (quantity, item ) { this .quantity = quantity; this .item = item; } getPrice ( ) { return this .getBasePrice () * this .getDiscountFactor (); } getBasePrice ( ) { return this .quantity * this .item .price ; } getDiscountFactor ( ) { return this .getBasePrice () > 1000 ? 0.95 : 0.98 ; }