【问题标题】:Avoiding $onlyActive boolean parameter避免 $onlyActive 布尔参数
【发布时间】:2014-08-11 01:32:56
【问题描述】:

我最近开始使用 phpmd 来检测不良编码习惯并加以修复。我的项目使用 Laravel 4 php 框架,并实现了存储库模式。

所以我有一个名为EloquentProductRepository 的类,它与我数据库中的产品表进行交互。像all() 方法这样的一些方法有一个名为$onlyActive 的布尔参数。如果为 true,则仅获取活动产品,否则将全部返回。

Phpmd 告诉我布尔参数是违反单一职责模式的某种标志。所以我做了一些阅读并同意应该避免布尔值。现在我的问题是在可维护性、可读性和可扩展性方面我应该如何重构它?

方法比较简单,如下所示

/**
 * Fetches all products
 *
 * @param boolean $onlyActive Flag for only returning active products
 * @return Collection
 */
public function all($onlyActive = true)
{
    if ($onlyActive)
    {
        return $this->model->where('active', true)->get();
    }

    return $this->model->all();
}

我看到了 2 个选项。一种是使用 $options 数组,而不是使用键“include_inactive”。另一个选项是创建 2 个方法。 all()allWithInactive()。我目前有 3 个使用 $onlyActive 布尔值的方法,所以最后一个选项会向我的类添加 3 个方法,这可能会使类在方法上相当大。 (phpmd 更喜欢类不超过 10 个公共方法)

【问题讨论】:

    标签: php methods laravel-4 boolean


    【解决方案1】:

    你基本上有两个不同的功能 - 所以我会这样做

    public function getAll()
    {
        return $this->model->all();
    }
    
    
    public function getOnlyActive()
    {
        return $this->model->where('active', true)->get();
    }
    

    注意函数名称 - getAll() 正是这样做的 - 所有记录,没有例外。 getOnlyActive() 正是这样做的——只有活动记录——该函数名称中没有“全部”,因为它没有得到“全部”。

    【讨论】:

    • 我将使用这种方法。似乎是最干净的一个。现在不要指望有更多选择。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    • 2014-02-24
    • 2022-10-05
    • 2014-10-17
    • 1970-01-01
    相关资源
    最近更新 更多