php OOP:在类的构造函数中做一些事情与调用私有方法来做同样的事情


php OOP: Doing something in a class's constructor vs calling a private method to do the same thing

在阅读各种教程时,我注意到了这两种不同的方法,我很好奇引擎盖下发生了什么。

第一种方法在构造函数中执行所有操作 - 所有内容都在设置变量,或者在这种情况下调用类的方法执行某些操作。第二种方法调用构造函数中的私有方法来执行相同的操作。什么时候一种方式比另一种方式更可取?我知道微优化是邪恶的,但在学术层面上,调用私有方法是否慢一点?

下面是第一种方法的代码示例(这是一些 zf2 代码):

class LoginForm extends Form
{
    public function __construct($name = null) {
        // we want to ignore the name passed
        parent::__construct('login-form');
        $this->setAttribute('method', 'post');
        $this->add(array(
            'name' => 'username',
            'attributes' => array(
                'type'=> 'text',
            ),
            'options' => array(
                'label' => 'User Name',
            ),
        )); ...

VS 这个:

class LoginForm extends Form
{
    public function __construct($name = null) {
        // we want to ignore the name passed
        parent::__construct('login-form');
        $this->setAttribute('method', 'post');
        $this->addElements();
    }
    private function addElements() {
        $this->add(array(
            'name' => 'username',
            'attributes' => array(
                'type'=> 'text',
            ),
            'options' => array(
                'label' => 'User Name',
            ),
        )); ...

不明白为什么这被标记了。我没有问哪种方式更好,我看到了一些我不完全理解的东西,并想听听一些可能的原因,为什么一个程序员可能以一种方式做,而另一个程序员用另一种方式做。接受的答案对我非常有帮助,因为它还指出了一种方法如何明显地存在可能的设计问题。

构造函数中的私有函数调用是代码异味的症状。要么函数很长 - 这就是你首先想要函数调用的原因 - 要么构造函数正在做一些它不应该做的事情。

在这种情况下,setAttributeaddElements似乎正在为对象设置一些默认值。还有其他方法可以实现此目的。

具体来看这个案例,你可能会争辩说LoginForm不应该是一个类。相反,你可以有一个函数:

function create_login_form() {
    $form = new Form();
    $form->setAttribute("method", "post");
    // etc
    return $form;
}

更仔细地观察这段代码:它似乎是HTML的某种包装器,这是有问题的。HTML非常擅长它所做的事情。它是一种DSL(域特定语言)。 LoginForm偏离了DSL的原始概念太远了。

如果你更进一步,你会得到:

function create_login_form() {
    $form = new HTML_Element("form");
    $form->setAttribute("method", "post");
    // etc
    return $form;
}

这对我来说看起来很合理。