メソッドのパラメータ化 (リファクタリング-p283)
リファクタリング
Published: 2019-03-03

目的

「リファクタリング」を理解するためにサンプルコードを PHP で書き換えてみました。

今回は「メソッドのパラメータ化」について書きます。

「メソッドのパラメータ化」 について

複数のメソッドが、異なる値に対してよく似た振る舞いをしている。

変更前

<?php

class Employee
{
    private $salary;

    public function __construct($salary)
    {
        $this->salary = $salary;
    }

    public function tenPercentRaise()
    {
        $this->salary *= 1.1;
    }

    public function fivePercentRaise()
    {
        $this->salary *= 1.05;
    }

    public function getSalary()
    {
        return $this->salary;
    }
}

$e1 = new Employee(1000);
$e1->tenPercentRaise();
echo $e1->getSalary() . "\n";

変更後

<?php

class Employee2
{
    private $salary;

    public function __construct($salary)
    {
        $this->salary = $salary;
    }

    public function raise($factor)
    {
        $this->salary *= (1 + $factor);
    }

    public function getSalary()
    {
        return $this->salary;
    }
}

$e2 = new Employee2(1000);
$e2->raise(0.1);
echo $e2->getSalary() . "\n";