考虑这段代码:
public void AddPrice(int exchangeTypeId, decimal price)
{
GoldPrice lastPriceValue = UnitOfWork.GoldPrice.Last(x => x.GoldId == exchangeTypeId);
if (lastPriceValue == null || lastPriceValue.Value != price)
{
UnitOfWork.GoldPrice.Add(
new GoldPrice
{
Id = Guid.NewGuid().ToString(),
EntryDate = DateTime.Now,
Value = price,
GoldId = exchangeTypeId,
}
);
}
else
{
lastPriceValue.EntryDate = DateTime.Now;
}
UnitOfWork.Commit();
}
在上面的代码中,我有一些业务,例如检查 null,获取最后价格和....所以考虑一下:
public void AddPrice(int exchangeTypeId, decimal price)
{
CurrencyPrice lastPriceValue = UnitOfWork.CurrencyPrice.Last(x => x.CurrencyId == exchangeTypeId);
if (lastPriceValue == null || lastPriceValue.Value != price)
{
UnitOfWork.CurrencyPrice.Add(
new CurrencyPrice
{
Id = Guid.NewGuid().ToString(),
EntryDate = DateTime.Now,
Value = price,
CurrencyId = exchangeTypeId,
}
);
}
else
{
lastPriceValue.EntryDate = DateTime.Now;
}
UnitOfWork.Commit();
}
我有两个具有完全相同业务的功能。如果业务发生变化,我应该更改每个添加价格功能那么我如何才能遵循业务代码的DRY原则?