减少大量方法参数的最佳实践/惯例

时间:2019-01-08 23:29:02

标签: php

我有如下方法:

public function updateContact(Contact $contact,
      string $accountNumber = null,
      string $contactStatus = 'ACTIVE',
      string $name = null,
      string $primaryPersonFirstName = null,
      string $primaryPersonLastName = null,
      string $primaryPersonEmail = null,
      string $defaultCurrency = null,
      string $taxNumber = null,
      string $postalAddress1 = null,
      string $postalAddress2 = null,
      string $postalCity = null,
      string $postalRegion = null,
      string $postalPostalCode = null,
      string $postalCountryName = null,
      string $streetAddress1 = null,
      string $streetAddress2 = null,
      string $streetCity = null,
      string $streetRegion = null,
      string $streetPostalCode = null,
      string $streetCountryName = null
) {

这些只是完成所有功能的一些可能参数。人们对减少论点清单的方式有何想法。我看到一些选择:

  • 采用单个阵列。缺点是用户需要知道什么进入数组,就像在参数列表中更明显。

  • 每种更新建议的方法,即public function updateAccountNumber($account_number)。缺点是所需的方法太多。

这种事情的一般约定是什么?

1 个答案:

答案 0 :(得分:1)

  

采用单个阵列。缺点是用户需要知道数组中的内容,就像在参数列表中更明显一样。

就像您建议的那样,我可能会通过类构造函数传递一个选项数组?

但是,要解决您所说的“用户需要知道数组中包含什么”,我会考虑创建某种函数来设置选项。

基本示例:

class Example {

  private $options = array();

  public function setOption($option, $value) {
    $this->options[$option] = $value;
  }

}

或者,如果您只想设置某些选项,则如下所示:

示例二:

class Example {

  private $options = array();
  private $acceptedOptions = array('accountNumber','contactStatus','name','and_so_on...');

  public function setOption($option, $value) {
    if (!in_array($option, $this->acceptedOptions)) return false;
    $this->options[$option] = $value;
    return $this->options;
  }

}

这样,您现在就可以像这样为您的课程设置选项:

$myClass = new Example;
$myClass->setOption('name', 'Jonathan');

您可以看到它是否也被接受,像这样:

$myClass = new Example;
$accepted = $myClass->setOption('name', 'Jonathan');
if (!$accepted) {
   // Yikes it didn't work.
}