对象构造函数除了分配其依赖项之外还有什么问题?

what is wrong with object constructor doing more than assigning its dependencies?

提问人:rahulaga-msft 提问时间:8/24/2019 更新时间:8/24/2019 访问量:34

问:

我看到了一些文字,上面写着“在构造函数中什么都不做,只分配属性......”,然后是重构代码之前和之后的下面。说实话,我一直在遵循这种做法,但想知道和理解一些更好的例子,如果不遵守这个准则,事情可能会出错。

重构前:

final class MySQLTableGateway
{
    private Connection connection;
    public function __construct(
        ConnectionConfiguration connectionConfiguration,
        string tableName
    ) {
        this.tableName = tableName;
        this.connect(connectionConfiguration);
    }
    private function connect(
        ConnectionConfiguration connectionConfiguration
    ): void {
        this.connection = new Connection(
            // ...
        );
    }
    public function insert(array data): void
    {
        this.connection.insert(this.tableName, data);
    }
}

重构版本

final class MySQLTableGateway
{
    private ConnectionConfiguration connectionConfiguration;  
    public function __construct(
        ConnectionConfiguration connectionConfiguration,
        string tableName
    ) {
        this.connectionConfiguration = connectionConfiguration;
        this.tableName = tableName;
    }
    private function connect(
        ConnectionConfiguration connectionConfiguration
    ): void {
        if (this.connection instanceof Connection) {
            return;                                             
        }
        this.connection = new Connection(
            // ...
        );
    }
    public function insert(array data): void
    {
        this.connect();                                       
        this.connection.insert(this.tableName, data);
    }
}
OOP 依赖注入 与语言无关的 编码风格

评论

0赞 RWRkeSBZ 8/24/2019
您从哪里读到本指南?难道他们没有解释原因吗?
0赞 rahulaga-msft 8/24/2019
@RWRkeSBZ不,他们没有解释——因此问题来了。
4赞 RWRkeSBZ 8/24/2019
所以,基本上他们提出了一个未经证实的说法:-)无论如何,避免在构造函数中做太多事情的原因是让我的对象尽快进入稳定状态,并且没有发生异常的风险。如果您的构造函数只是一长串构造链中的一个,则异常可能会使问题复杂化。因此,准则是尽快创建对象,并尽可能降低发生异常的风险。

答: 暂无答案