提问人:rahulaga-msft 提问时间:8/24/2019 更新时间:8/24/2019 访问量:34
对象构造函数除了分配其依赖项之外还有什么问题?
what is wrong with object constructor doing more than assigning its dependencies?
问:
我看到了一些文字,上面写着“在构造函数中什么都不做,只分配属性......”,然后是重构代码之前和之后的下面。说实话,我一直在遵循这种做法,但想知道和理解一些更好的例子,如果不遵守这个准则,事情可能会出错。
重构前:
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);
}
}
答: 暂无答案
下一个:关于继承的一些困惑
评论