构造函数设计——在构造函数中加载数据(c#)

本文关键字:构造函数 数据 加载 | 更新日期: 2023-09-27 18:12:00

我有一种"感觉",我在构造函数中调用方法来加载数据的设计是不正确的。

我尝试编写一个类,该类提供了基本逻辑,以便为发票、订单或报价记录执行计算(折扣、税、总金额等)。在大多数情况下,需要相同的一组属性(例如,属性"quantity"出现在所有实体/表中)。

在我目前的设计是使用这个基类(注意,这不是真正的代码,我在家里,没有访问代码库,所以可能有拼写错误):

public abstract class HeadCalculationEngineBase
{
    protected readonly IOrganisationService orgService;
    protected decimal pricePerUnit;
    protected decimal quantity;
    public HeadCalculationEngineBae(Guid entityid, IOrganisationService service)
    {
        this.orgService = service;
        this.populate(this.loadEntityData(id));
    }
    public virtual Entity loadEntityData(Guid id)
    {
        var columns = new ColumnSet("pricePerUnit", "quantity");
        return this.orgService.Retrieve(id, columns);
    }
    protected virtual populate(Entity data)
    {
        this.pricePerUnit = data["pricePerUnit"];
        this.quantity = data["quantity"];
    }
}

这个设计为我提供了覆盖虚拟成员和为发票实体的实现加载附加属性的选项:

public class HeadCalculationInvoiceEngine : HeadCalculationEngineBase
{
    protected decimal discount;
    public HeadCalculationInvoiceEngine(Guid entityid, IOrganisationService service)
        :base(entityid, service)
    { }
    public override Entity loadEntityData(Guid id)
    {
        var columns = new ColumnSet("pricePerUnit", "quantity", "discount");
        return this.orgService.Retrieve(id, columns);
    }
    protected override populate(Entity data)
    {
        this.pricePerUnit = data["pricePerUnit"];
        this.quantity = data["quantity"];
        this.discount = data["discount"];
    }
} 

所以我的问题归结为:我应该在构造函数中加载数据吗?

构造函数设计——在构造函数中加载数据(c#)

最好保持构造函数轻量级,避免长时间调用,尤其是远程调用。

  • 构造函数中的失败比方法抛出的异常更难解释。
  • 在单元测试中模拟这样的功能比较困难(例如,你不能提取构造函数到接口)
  • 构造函数不能是异步的-所以当你尝试切换到现代异步api来访问远程资源时,你将不得不显著修改你构造对象的方式。