我有种感觉,我的设计调用一种方法来在构造函数中加载数据是不正确的.
I have the "feeling" that my design to invoke a method to load data inside the constructor is not right.
我尝试编写一个提供基本逻辑的类,以对发票,订单或报价记录进行计算(折扣,税金,总金额等).在大多数情况下,需要使用相同的属性集(例如,所有实体/表中都存在属性"quantity").
I try to write a class that provides the basic logic to perform a calculation (discount, tax, total-amount etc.) for invoices-, orders- or quotes-record. In most cases are the same set of attributes needed (e.g. the attribute "quantity" is present in all entities/tables).
在我当前的设计中,使用此基类(请注意,这不是真正的代码,我在家里,无法访问代码库,因此可能出现错字):
In my current design is use this base class (note this is not the real code, i am at home and do not have access to the code-base, so typos are likely):
public abstract class HeadCalculationEngineBase { protected readonly IOrganisationService orgService; protected decimal pricePerUnit; protected decimal quantity; public HeadCalculationEngineBae(Guid entityid, IOrganisationService service) { thisService = service; this.populate(this.loadEntityData(id)); } public virtual Entity loadEntityData(Guid id) { var columns = new ColumnSet("pricePerUnit", "quantity"); return thisService.Retrieve(id, columns); } protected virtual populate(Entity data) { this.pricePerUnit = data["pricePerUnit"]; this.quantity = data["quantity"]; } }这种设计使我可以选择覆盖虚拟成员并为发票实体的实现加载其他属性:
This design gives me the option to override the virtual member and load additional attributes for my implementation for the invoice entity:
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 thisService.Retrieve(id, columns); } protected override populate(Entity data) { this.pricePerUnit = data["pricePerUnit"]; this.quantity = data["quantity"]; this.discount = data["discount"]; } }所以我的问题归结为一个问题:我应该在构造函数中加载数据吗?
So my problem comes down to the question: Should I load data inside the constructor?
推荐答案更好地使构造函数保持轻量级,并避免长时间(尤其是远程)调用.
Better to keep constructors lightweight and avoid long and especially remote calls.
- 构造方法中的故障比方法抛出的异常更难以推理.
- 要为单元测试模拟这样的功能更加困难(例如,您无法提取构造函数以进行接口连接)
- 构造器不能是异步的-因此,当您尝试切换到现代异步API来访问远程资源时,您将不得不显着修改构造对象的方式.
更多推荐
构造函数设计
发布评论