Introduce Explaining Variable
Motivation
复杂的表达式是很难阅读的,不仅如此,很多时候由于表达式太长而不得不换行书写,也影响代码的美化。
比如 If 括号中的条件表达式,如果太长的话,我们可以把表达式拆分为几个小的表达式,并赋值给不同的临时变量,这样代码将会显得清晰美观,易于阅读。
Example Code
1 2 3 4 5 6 7 8 | function price() { // price is base price - quantity discount + extra fee return $this->quantity * $this->item_price - max(0, $this->quantity - 200) * $this->item_price * 0.08 + min($this->quantity * $this->item_price * 0.1, 100.0); } /* vim: set expandtab tabstop=4 shiftwidth=4: */ |
是不是又臭又长很难读啊?下面我们试着把表达式拆分:
1 2 3 4 5 6 7 8 | function price() { $price = $this->quantity * $this->item_price; $discount = max(0, $this->quantity-200) * $this->item_price * 0.08; $fee = min($basePrice * 0.1, 100.0); return $price - $discount + $fee; } /* vim: set expandtab tabstop=4 shiftwidth=4: */ |
上面的重构的代码,已经达到了我们的目的,下面我们来尝试一下新的重构方式:Extract Methods,把表达式拆分为一个个小的函数(或方法)。
拆分成函数和拆分为变量可以达到相同的效果,但如果我们需要达到重用的效果,Extract Methods 更适合,再看下面的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | function getPrice() { return $this->price() - $this->discount() + $this->fee(); } // Extract as methods function price() { return $this->quantity * $this->item_price; } function discount() { return max(0, $this->quantity - 200) * $this->item_price * 0.08; } function fee() { return min($this->price() * 0.1, 100.0); } /* vim: set expandtab tabstop=4 shiftwidth=4: */ |
在这个例子中,Extract Methods 比 Explaining Variables 更好用,但并不代表所有的情况,还是那句话:具体问题具体分析。
使用哪种重构方法,还要看具体的情况而定。