最佳实践:构造函数可以复杂吗?

时间:2016-08-14 02:41:14

标签: constructor software-design

我有以下课程

class Car{
 String modelName;
 Headlight headlight;
 Wiper wiper;

public Car(String modelName){
 this.modelName = modelName;
 this.headlight = HeadlightDao.findByModelName(modelName).getHeadlight();
 this.wiper = WiperDao.findByModelName(modelName).getWiper();
 }
}

在构造函数中有太多的构造逻辑是错误的(读取反模式)吗?

如果我提取数据库连接,则对象将不再保持不可变。

如果我事先创建了Wiper和Headlight,那么我将向客户公开案例内容的细节吗?

1 个答案:

答案 0 :(得分:0)

构造函数不应该很复杂。

构造函数的想法是协助创建新对象。我会将你的代码重写为类似的东西

class Headlight{
    string modelName;

    public Headlight(string _modelName){
        this.modelName = _modelName;
    }
}

class Wiper{
    string modelName;

    public Wiper(string _modelName){
        this.modelName = _modelName;
    }
}

class Car{
    string modelName;
    Headlight headlight;
    Wiper wiper;

    public Car(string _modelName)
    {
         this.modelName = _modelName;
         this.headlight = new Headlight(modelName);
         this.wiper = new Wiper(modelName);
    }
}

我知道这看起来没有意义但是你的代码看起来像是从存储库中获取默认值所以如果需要在其他地方获取默认值那么我认为你可以自由使用你的代码。但是,如果您通过modelName获取汽车详细信息,则应该具有以下内容:

class Car{
   string modelName;
   Headlight headlight;
   Wiper wiper;

   public Car(){
   }

   public Car(string _modelName, Headlight _headlight, Wiper _wiper){
        this.modelName = _modelName;
        this.headlight = _headlight;
        this.wiper = _wiper;
   }

}

class carService{
   public Car getCarByModel(string modelName){
       //this is just a sample code where you get something from your repository
       var carDAO = repoService.getCarByModel(modelName);
       return new Car(carDAO.modelName, carDAO.headlight, carDAO.wiper);
   }
}