我应该在哪里放置构造函数的公共代码?

时间:2018-04-12 11:38:54

标签: java constructor

我有一种情况,在类中我有2个构造函数,它们的代码非常相似。唯一的区别是对超类构造函数的调用。我应该在哪里放置这个通用代码?我试图使用实例块但是使用实例块我无法传递所需的参数。

此外,这些字段是最终的。所以不能初始化其他构造函数。

我的代码如下:

$browser->assertUrlIs($b);

3 个答案:

答案 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);
}