規範 - 只使用一層縮排

心智極客發表於2019-12-28

定義一個類用於管理銀行賬戶

<?php
class BankAccount {

    protected $accounts;

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

    public function filterBy($accountType)
    {
        $filtered = [];
        // 1
        foreach ($this->accounts as $account) {
            // 2
            if ($account->type() == $accountType) {
                // 3
                if ($account->isActive()) {
                    $filtered[] = $account;
                }
            }
        }
        return $filtered;
    }
}

class Account {

    protected $accounts;

    protected $type;

    private function __construct($type)
    {
        $this->type = $type;
    }

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

    public function isActive()
    {
        return true;
    }

    public static function open($type)
    {
        return new static($type);
    }

}

測試

$accounts = [
    Account::open('checking'),
    Account::open('savings'),
    Account::open('checking'),
    Account::open('savings')
];
$bankAccounts = new BankAccount($accounts);
$savings = $bankAccounts->filterBy('checking');

BankAccount 類的 filterBy 方法用於過濾賬戶型別,該方法包括了三層縮排。

簡化一,將判斷邏輯剝離出來

class BankAccount {
    protected $accounts;
    public function __construct($account)
    {
        $this->accounts = $account;
    }

    public function filterBy($accountType)
    {
        $filtered = [];
        foreach ($this->accounts as $account) {
            if ($this->isOfType($accountType, $account)) {
                $filtered[] = $account;
            }
        }
    }

    public function isOfType($accountType, $account)
    {
        return $account->type() == $accountType && $account->isActive();
    }
}

簡化二:將判斷邏輯交給子類

class BankAccounts {

    public function filterBy($accountType)
    {
        return array_filter($this->accounts, function($account) use($accountType)
        {
            return $account->isOfType($accountType);
        });
    }
}

class Account {

    public function isOfType($accountType)
    {
        return $this->type() == $accountType && $this->isActive();

    }
}

來源:Laracasts

點選 連結,加入心智極客的技術分享群

相關文章