次のコードを検討してください。
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();
}
まったく同じビジネスを持つ 2 つの関数があります。ビジネスが変更された場合は、価格関数を追加するたびに変更する必要があります。では、ビジネス コードのDRY原則に従うにはどうすればよいでしょうか。