“如果规则存在是因为业务需要,那么它属于域”
本着 DDD 的精神,将所有计算都放在您的域中。
域有时被称为“业务层”是有原因的,因为它包含所有相关的业务逻辑/规则。
以下代码是纯 DDD 的示例。每次添加订单时都会自动完成总计算,您不必担心忘记显式调用“计算例程”。
public class Order
{
public void AddItem(Item item)
{
// Do add item here
this.CalculateTotal(); // At the end, calculate total.
}
private void CalculateTotal()
{
// Do calculations
this.Total = 0; // after calculations, assign new value;
}
public decimal Total { get; private set; } // notice the "private" setter?
}
您不必担心计算,让您可以将精力集中在其他事情上。
如果您需要更改计算,您只需转到包含业务逻辑的地方即可。欢迎来到领域驱动设计^_^
更新
以下是针对增值税评论的更新代码。
增值税
同样,增值税的计算是在 CalculateTotal() 内自动完成的
如果增值税取决于每个国家/地区,则只需创建一个具有增值税属性的国家/地区。将 country 属性放在 Customer 上,如下所示:
public class Customer
{
public Country Country { get; set; }
}
public class Country
{
public string Name { get; set; } // Country Name
public decimal Vat { get; set; }
}
在CalculateTotal() 中,只需根据客户所在的国家/地区检查他们是否受到增值税的影响。
public class Order
{
public void AddItem(Item item)
{
// Do add item here
this.CalculateTotal(); // At the end, calculate total.
}
private void CalculateTotal()
{
// Do calculations
// Get Vat
decimal vat = this.Customer.Country.Vat;
this.Total = 0; // after calculations, assign new value;
}
public Customer Customer { get; set; }
public decimal Total { get; private set; } // notice the "private" setter?
}
如果您打算更改增值税,那么您知道去哪里找(当然是国家)
增值税的任何变化都会影响该国家/地区的所有客户。