在将值作为参数传递之前,我应该在哪里检查值是否正确


Where should I check that the values are right, in the constructor or before passing the values as arguments?

假设我正在编写一个将进行基本 CRUD 操作的类,因此我希望将要插入到数据库的所有值都为小写。因此,我确保构造函数中的值全部为小写,例如:

class Insert {
  private $name;
  private $lastname;
  public function __construct($name, $lastname) {
    $this->name = strtolower($name);
    $this->name = strtolower($lastname);
  }
}
$obj = new Insert('Jhon', 'Doe');

或者在创建实例之前,如下所示:

class Insert {
  private $name;
  private $lastname;
  public function __construct($name, $lastname) {
    $this->name = $name;
    $this->name = $lastname;
  }
}
$obj = new Insert(strtolower('Jhon'), strtolower('Doe'));

我会设置一个 DTO 来格式化值。更具可读性,您的类不需要知道是否更慢,只需设置变量即可。

DTO 类:

class UserDto
{
    public $lastname;
    public $name;
    function __construct($name, $lastname)
    {
       $this->lastname = strtolower($lastname);
       $this->name = strtolower($name);
    }
}

然后你可以做

$userDto = new UserDto('Jhon', 'Doe');
$obj = new Insert($userDto);
$obj->save();

class Insert
{
    private $name;
    private $lastname;
    public function __construct($userDto)
    {
        $this->name = $userDto->name;
        $this->lastname = $userDto->lastname;
    }
}

现在,如果有时您需要不再需要名称和姓氏,那么您唯一需要做的就是更改类 DTO,而不会影响插入类。