定义一个类用于管理银行账户
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 协议》,转载必须注明作者和本文链接