规范 - 只使用一层缩进

定义一个类用于管理银行账户

<?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

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 2

如果能用一个类内搞定的业务,不要更多的类来搞定,每多一层外部调用,你都会思考他们会可能被哪些类调用。

4年前 评论
心智极客 (楼主) 4年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!