条件記述の分解 (リファクタリング-p238)
リファクタリング
Published: 2018-12-24

目的

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

今回は「条件記述の分解」について書きます。

変更前

<?php

date_default_timezone_set('Asia/Tokyo');

class Dummy
{
    private $_winterRate = 0.6;
    private $_summerRate = 0.2;
    private $_winterServiceCharge = 250;

    const SUMMER_START = '2018/07/01 00:00:00';
    const SUMMER_END = '2018/08/31 23:59:59';

    public function calcCharge($quantity)
    {
        $now = time();
        if (strtotime(self::SUMMER_START) > $now ||
            strtotime(self::SUMMER_END) < $now) {
            return $quantity * $this->_winterRate * $this->_winterServiceCharge;
        }

        return $quantity * $this->_summerRate;
    }
}

$d = new Dummy();
echo $d->calcCharge(10) . "\n";

変更後

<?php

date_default_timezone_set('Asia/Tokyo');

class Dummy2
{
    private $_winterRate = 0.6;
    private $_summerRate = 0.2;
    private $_winterServiceCharge = 250;

    const SUMMER_START = '2018/07/01 00:00:00';
    const SUMMER_END = '2018/08/31 23:59:59';

    public function calcCharge($quantity)
    {
        if ($this->notSummer()) {
            return $this->winterCharge($quantity);
        }

        return $this->summerCharge($quantity);
    }

    private function notSummer()
    {
        $now = time();
        return (strtotime(self::SUMMER_START) > $now) ||
            (strtotime(self::SUMMER_END) < $now);
    }

    private function summerCharge($quantity)
    {
        return $quantity * $this->_summerRate;
    }

    private function winterCharge($quantity)
    {
        return $quantity * $this->_winterRate * $this->_winterServiceCharge;
    }
}

$d = new Dummy2();
echo $d->calcCharge(10) . "\n";