如何遵循业务代码的DRY原则

时间:2013-06-28 16:00:17

标签: c# dry

考虑以下代码:

    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 原则来处理业务代码?

2 个答案:

答案 0 :(得分:0)

看看Strategy Pattern

答案 1 :(得分:0)

你可以重构一组基本的抽象来获得价格。

public interface IPrice
{
    string Id { get; set; }
    DateTime EntryDate { get; set; }
    decimal Value { get; set; }
    int ExchangeTypeId { get; set; }
}

public interface IUnitOfWork<T>
    where T: IPrice
{
    T GetLatest(int exchangeTypeId);
    void Add(T price);
    void Commit();
}

public interface IUnitOfWorkFactory
{
    void Register<T>() where T: IPrice;
    IUnitOfWork<T> Get<T>() where T: IPrice;
}

public void AddPrice<T>(int exchangeTypeId, decimal price)
    where T: IPrice, new()
{
    IUnitOfWork<T> unitOfWork = _unitOfWorkFactory.Get<T>();
    IPrice lastPriceValue = unitOfWork.GetLatest(exchangeTypeId);

    if (lastPriceValue == null || lastPriceValue.Value != price)
    {
        unitOfWork.Add(
            new T
            {
                Id = Guid.NewGuid().ToString(),
                EntryDate = DateTime.Now,
                Value = price,
                ExchangeTypeId = exchangeTypeId,
            });
    }
    else
    {
        lastPriceValue.EntryDate = DateTime.Now;
    }

    unitOfWork.Commit();
}