构造函数设计

编程入门 行业动态 更新时间:2024-10-28 00:23:05
本文介绍了构造函数设计-在构造函数内部加载数据(C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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来访问远程资源时,您将不得不显着修改构造对象的方式.

更多推荐

构造函数设计

本文发布于:2023-10-25 03:11:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1525749.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!