C # Оптимизация создания нового объекта (слишком много, некрасивый код)

1

Я боюсь, что этот вопрос может быть глупым/я не совсем так, как спросить об этом, но здесь мы идем:

В настоящее время я работаю над проектом, где мне нужно создать много новых объектов. Свойства задаются несколькими ifs, и код выглядит очень грязным для меня.

/// <summary>
/// Creates a new <see cref="StockItem"/> based on the <see cref="Article"/> of the given <param name="input"/>.
/// </summary>
/// <param name="input"></param>
public static StockItem CreateStockItem(InputParameterCreateStockItem input)
{
    var returnStockItem = new StockItem();

    //If there is an imob item, start from there and update everything
    if (input.StockItem != null)
    {
        returnStockItem = input.StockItem;
    }
    else
    {
        //When creating a stock item, the status is ALWAYS 1
        returnStockItem.Status = 1;
    }

    #region Properties
    returnStockItem.PartTypeNo = (Int32)input.Article.ArticleNumberPrefix + "-" + input.Article.ArticleNumber.Value.ToString("D8");
    returnStockItem.Kardex = ConvertHelper.GetTechSpecValue(input.Article.TechnicalSpecifications, ConvertHelper.KardexT) ?? String.Empty;
    returnStockItem.WeldNumber = input.WeldNumber;
    returnStockItem.ObjectNo = ConvertHelper.GetTechSpecValue(input.Article.TechnicalSpecifications, ConvertHelper.ObjectNoT) ?? ConvertHelper.GetObjectNo(input.Article);
    returnStockItem.Synonymous = ConvertHelper.GetTechSpecValue(input.Article.TechnicalSpecifications, ConvertHelper.SynonymousT) ?? String.Empty;
    returnStockItem.ExtSerialNo = ConvertHelper.GetTechSpecValue(input.Article.TechnicalSpecifications, ConvertHelper.ExtSerialNoT) ?? String.Empty;
    returnStockItem.ArticleReference = (ConvertHelper.GetTechSpecValue(input.Article.TechnicalSpecifications, ConvertHelper.ArticleReferenceT)) ??
                                   ConvertHelper.RemoveColorCodeFromReference(input.Article.Reference, input.ColorList);
    returnStockItem.ArticleName = ConvertHelper.GetTechSpecValue(input.Article.TechnicalSpecifications, ConvertHelper.ArticleNameT) ??
                              ConvertHelper.GetCorrectTranslation(input.Article.Names, "ENG");
    returnStockItem.Length = ConvertHelper.GetMeasurementInMeters(input.Article, ConvertHelper.ImobLengthT, ConvertHelper.ClsLengthT);
    returnStockItem.Width = ConvertHelper.GetMeasurementInMeters(input.Article, ConvertHelper.ImobWidthT, ConvertHelper.ClsWidthT);
    returnStockItem.Height = ConvertHelper.GetMeasurementInMeters(input.Article, ConvertHelper.ImobHeightT, ConvertHelper.ClsHeightT);
    returnStockItem.Weight =
        Decimal.Parse(!String.IsNullOrEmpty(ConvertHelper.GetTechSpecValue(input.Article.TechnicalSpecifications, ConvertHelper.ImobWeightT))
            ? ConvertHelper.GetTechSpecValue(input.Article.TechnicalSpecifications, ConvertHelper.ImobWeightT)
            : ConvertHelper.GetTechSpecValue(input.Article.TechnicalSpecifications, ConvertHelper.ClsWeightT) ?? "0");
    returnStockItem.DepreciationCode = ConvertHelper.GetTechSpecValue(input.Article.TechnicalSpecifications, ConvertHelper.DepreciationCodeT) ??
                                   (input.Article.DepreciationCode != null ? input.Article.DepreciationCode.InsuranceValueCode.ToString() +
                                    input.Article.DepreciationCode.ActualValueCode.ToString() +
                                    input.Article.DepreciationCode.RevaluationCode.ToString() : String.Empty);
    returnStockItem.Value = ConvertHelper.GetValue(input.Article);
    returnStockItem.ValueDate = ConvertHelper.GetValueDate(input.Article);
    returnStockItem.Brand = ConvertHelper.GetBrand(input.Article);
    returnStockItem.Remarks = ConvertHelper.GetRemarks(input.Article);
    returnStockItem.InsuranceValue = ConvertHelper.GetInsuranceValue(input.Article);
    returnStockItem.StockItemGroupID = ConvertHelper.GetStockItemGroupId(input.Article, input.ClsImobArticleGroups, input.StockItemGroups);
    returnStockItem.StockAllocations = StockAllocationDAO.GetStockAllocationsForArticleGroupIDs(input.Article, input.ClsAssignedArticleGroups, input.ClsUnAssignedArticleGroups, input.ClsImobArticleGroups, input.StockAllocationsDictionaryByCode, input.StockAllocationsDictionaryByName);
    #endregion

    //AddMotherStockItemColorCode(input.Article, stockItem);

    return returnStockItem;
}

Мне интересно, есть ли лучший (более читаемый) способ сделать это.

Вещи, которые я уже сделал:

  • Переместил более сложный код в класс помощника (ConvertHelper)
  • Создал объект входных параметров (мне нужно было много списков для проверки определенных вещей)
  • Переместил весь метод на фабрику (не нужен?)

Но все это мне кажется бесполезным.

Спасибо, Томас

  • 3
    может быть, это лучше для CodeReview ( codereview.stackexchange.com )? Вы также должны уточнить, что вы имеете в виду с «лучше»? удобочитаемость / производительность и т. д.
  • 0
    Вы должны иметь возможность удалить ConvertHelper из ConvertHelper.GetMeasurementInMeters, если вы правильно используете
Показать ещё 8 комментариев
Теги:
getter-setter
constructor

1 ответ

4

Вы пробовали AutoMapper? https://github.com/AutoMapper/AutoMapper Потратьте некоторое время на просмотр документации, которую вы увидите, и получите это время очень быстро.

  • 0
    Спасибо за предложение, я его прочитаю!

Ещё вопросы

Сообщество Overcoder
Наверх
Меню