目的
「リファクタリング」を理解するためにサンプルコードを PHP で書き換えてみました。
今回は「メソッドオブジェクトによるメソッドの置き換え」について書きます。
「メソッドオブジェクトによるメソッドの置き換え」 について
メソッドの分解を困難にするのはローカル変数です。
例
変更前
class Account
{
public function gamma($inputVal, $quantity, $yearToDate)
{
$importantValue1 = ($inputVal * $quantity) + $this->delta();
$importantValue2 = ($inputVal * $yearToDate) + 100;
if (($yearToDate - $importantValue1) > 100) {
$importantValue2 -= 20;
}
$importantValue3 = $importantValue2 * 7;
return $importantValue3 - 2 * $importantValue1;
}
private function delta()
{
return 200;
}
}
$a1 = new Account();
echo $a1->gamma(100, 3, 22) . "\n";
変更後
class Account2
{
public function gamma($inputVal, $quantity, $yearToDate)
{
return (new Gamma($this, $inputVal, $quantity, $yearToDate))->compute();
}
public function delta()
{
return 200;
}
}
class Gamma
{
private $_account;
private $inputVal;
private $quantity;
private $yearToDate;
private $importantValue1;
private $importantValue2;
private $importantValue3;
public function __construct(Account2 $source, $inputVal, $quantity, $yearToDate)
{
$this->_account = $source;
$this->inputVal = $inputVal;
$this->quantity = $quantity;
$this->yearToDate = $yearToDate;
}
public function compute()
{
$importantValue1 = ($this->inputVal * $this->quantity) + $this->_account->delta();
$importantValue2 = ($this->inputVal * $this->yearToDate) + 100;
if (($this->yearToDate - $importantValue1) > 100) {
$importantValue2 -= 20;
}
$importantValue3 = $importantValue2 * 7;
return $importantValue3 - 2 * $importantValue1;
}
}
$a2 = new Account2();
echo $a2->gamma(100, 3, 22) . "\n";