我有一种情况,在类中我有2个构造函数,它们的代码非常相似。唯一的区别是对超类构造函数的调用。我应该在哪里放置这个通用代码?我试图使用实例块但是使用实例块我无法传递所需的参数。
此外,这些字段是最终的。所以不能初始化其他构造函数。
我的代码如下:
$browser->assertUrlIs($b);
答案 0 :(得分:3)
如果您的实例字段是最终字段,我只会让没有filesize
的构造函数调用第二个字段并传入0
/ null
值。
另外,为什么要在子类中分配事务?你不把它传给父母吗?
private final SourceCache sourceCache;
private final ServiceCache serviceCache;
private final MethodCache methodCache;
private final ModelCache modelCache;
private final QueryFactory queryFactory;
public MetaDataPersistenceHandler(
final Transaction transaction)
{
this(transaction, 0L); // Call the whole constructor below?
}
public MetaDataPersistenceHandler(
final Transaction transaction,
final long fileSize)
{
super(transaction, fileSize);
this.transaction = transaction; // Why are we setting this again?
this.sourceCache = new SourceCache(transaction);
this.serviceCache = new ServiceCache(transaction);
this.methodCache = new MethodCache(transaction);
this.modelCache = new ModelCache(transaction);
this.queryFactory = new QueryFactory();
this.transaction.addQueryFactory(this.queryFactory);
}
答案 1 :(得分:1)
将其移至私人构造函数。
编辑:这是一个例子
public MetaDataPersistenceHandler(
final Transaction transaction) {
super(transaction);
this.transaction = transaction;
MetaDataPersistenceHandler();
}
public MetaDataPersistenceHandler(
final Transaction transaction,
final long fileSize) {
super(transaction, fileSize);
this.transaction = transaction;
MetaDataPersistenceHandler();
}
private void MetaDataPersistenceHandler(){
this.sourceCache = new SourceCache(transaction);
this.serviceCache = new ServiceCache(transaction);
this.methodCache = new MethodCache(transaction);
this.modelCache = new ModelCache(transaction);
this.queryFactory = new QueryFactory();
this.transaction.addQueryFactory(this.queryFactory);
}
答案 2 :(得分:0)
更好的方法是使用Optional而不是0或null。
private final SourceCache sourceCache;
private final ServiceCache serviceCache;
private final MethodCache methodCache;
private final ModelCache modelCache;
private final QueryFactory queryFactory;
public MetaDataPersistenceHandler(
final Transaction transaction)
{
this(transaction, Optional.<Long>absent()); // Call the whole constructor below?
}
public MetaDataPersistenceHandler(
final Transaction transaction,
final Optional<Long> fileSize)
{
super(transaction, (fileSize.isPresent() ? fileSize.get() : 0));
this.transaction = transaction; // Why are we setting this again?
this.sourceCache = new SourceCache(transaction);
this.serviceCache = new ServiceCache(transaction);
this.methodCache = new MethodCache(transaction);
this.modelCache = new ModelCache(transaction);
this.queryFactory = new QueryFactory();
this.transaction.addQueryFactory(this.queryFactory);
}