【问题标题】:Refactor Duplicate Lambda Expressions重构重复的 Lambda 表达式
【发布时间】:2013-01-23 00:38:10
【问题描述】:

所以我们有两种方法如下所示:

方法一

private IEnumerable<object> CreateCentreViewModelForExport(IQueryable<CentreTranslation> centreTranslation)
{
    return centreTranslation.Select(s => new
    {
        id = s.Centre.id,
        centreTranslationId = s.id,
        name = s.Centre.name,
        number = s.Centre.number,
        date_opened = s.Centre.date_opened,
        address_line_1 = s.address_line_1,
        address_line_2 = s.address_line_2,
        address_line_3 = s.address_line_3,
        city = s.city,
        county = s.county,
        country = s.Centre.Country.name,
        //country_id = s.Centre.country_id,
        translatedCountry = s.country,
        postcode = s.postcode,
        hidden = !(s.Centre.CentreStatus.Where(w => w.environment_id == 4).FirstOrDefault().active),
        about = s.about,
        virtualTour = s.Centre.virtual_tour,
        directions = s.directions,
        phone = s.Centre.phone,
        fax = s.Centre.fax,
        email = s.Centre.email,
        lat = s.Centre.position.Latitude,
        lng = s.Centre.position.Longitude,
        imageCount = s.Centre.image_count,
        translatedCentreName = s.name,
        amenities = s.amenities ,
        features = s.FeatureTranslations.Select(s2 => new FeatureViewModel()
        {
            id = s2.id,
            name = s2.Feature.name,
            selected = s2.selected
        }),
        businessCentreAbout = s.ProductTranslations.Where(w => w.Product.id == (int)Products.BusinessCentre).FirstOrDefault().about,
        officeSpaceAbout = s.ProductTranslations.Where(w => w.Product.id == (int)Products.OfficeSpace).FirstOrDefault().about,
        virtualOfficeAbout = s.ProductTranslations.Where(w => w.Product.id == (int)Products.VirtualOffice).FirstOrDefault().about,
        meetingRoomsAbout = s.ProductTranslations.Where(w => w.Product.id == (int)Products.MeetingRooms).FirstOrDefault().about,
        businessLoungeAbout = s.ProductTranslations.Where(w => w.Product.id == (int)Products.BusinessLounge).FirstOrDefault().about,
        dayOfficeAbout = s.ProductTranslations.Where(w => w.Product.id == (int)Products.DayOffice).FirstOrDefault().about,
        language_group = s.Language.language_group,
        culture = s.Language.cuture
    });
}

方法二

private IQueryable<CentreViewModel> CreateCentreViewModel(IQueryable<CentreTranslation> centreTranslation)
{
    return centreTranslation.Select(s => new CentreViewModel()
    {
        id = s.Centre.id,
        centreTranslationId = s.id,
        name = s.Centre.name,
        number = s.Centre.number,
        date_opened = s.Centre.date_opened,
        address_line_1 = s.address_line_1,
        address_line_2 = s.address_line_2,
        address_line_3 = s.address_line_3,
        city = s.city,
        county = s.county,
        //country = s.Centre.Country.name,
        country_id = s.Centre.country_id,
        translatedCountry = s.country,
        postcode = s.postcode,
        hidden = !(s.Centre.CentreStatus.Where(w => w.environment_id == 4).FirstOrDefault().active),
        about = s.about,
        virtualTour = s.Centre.virtual_tour,
        directions = s.directions,
        phone = s.Centre.phone,
        fax = s.Centre.fax,
        email = s.Centre.email,
        lat = s.Centre.position.Latitude,
        lng = s.Centre.position.Longitude,
        imageCount = s.Centre.image_count,
        translatedCentreName = s.name,
        amenities = s.amenities,
        features = s.FeatureTranslations.Select(s2 => new FeatureViewModel()
        {
            id = s2.id,
            name = s2.Feature.name,
            selected = s2.selected
        }),
        businessCentreAbout = s.ProductTranslations.Where(w => w.Product.id == (int)Products.BusinessCentre).FirstOrDefault().about,
        officeSpaceAbout = s.ProductTranslations.Where(w => w.Product.id == (int)Products.OfficeSpace).FirstOrDefault().about,
        virtualOfficeAbout = s.ProductTranslations.Where(w => w.Product.id == (int)Products.VirtualOffice).FirstOrDefault().about,
        meetingRoomsAbout = s.ProductTranslations.Where(w => w.Product.id == (int)Products.MeetingRooms).FirstOrDefault().about,
        businessLoungeAbout = s.ProductTranslations.Where(w => w.Product.id == (int)Products.BusinessLounge).FirstOrDefault().about,
        dayOfficeAbout = s.ProductTranslations.Where(w => w.Product.id == (int)Products.DayOffice).FirstOrDefault().about
    });
}

可以看出有很多重复的代码。第二种方法返回一个强类型视图模型,而第一种方法由于包含两个额外属性(语言组和文化)而返回一个对象。

第二种方法用于填充 MVC 视图,第二种方法用于导出到 Excel 函数。 重构此因素以尽量减少重复的最佳方法是什么?

【问题讨论】:

  • 总是使用CentreViewModel,如果不需要languageculture 则留空?
  • 更适合Code Review
  • 从一半的答案看来,我应该放弃
  • 一般来说,匿名类不应该离开定义它们的方法。

标签: c# asp.net-mvc lambda


【解决方案1】:

我将创建一个 DTO 类并在其上设置一个接收 IQueryable centerTranslation 的 setter 方法。然后,您将对象传递给该类并在该类中设置所有这些值,并将 dto 传递回您在那里拥有的原始方法。

    public class SomeDto
    {
        //All of the properties your setting in the other method

        public void SetDto(IQueryable<CentreTranslation> centreTranslation)
        {
            //call methods that set all the properties
        }

        private SetAddress(IQueryable<CentreTranslation> centreTranslation)
        {
            //set only address properties
        }

我还会为类型创建更小的 setter 方法,例如与地址有关的所有内容,在 dto 对象上创建一个名为 SetAddress 的私有方法并继续下去。

拥有 DTO 对象后,您可以使用 Automapper 之类的工具直接从 DTO 对象映射到 ViewModel 对象。这将为您在整个应用程序中进行更多重构提供最大的灵活性。

 private ViewModel createViewModel(Dto)

 {
     return Mapper.Map(Dto, ViewModel);    
 }

【讨论】:

  • 我确实喜欢 Automapper,但我无法完全想象您在这里所说的内容 :)
【解决方案2】:

在 CentreViewModel 类中创建一个静态的FromCentreTranslation 方法,并将所有初始化都放在那里:

public class CentreViewModel 
{
   ....
   public static CentreViewModel FromCentreTranslation(CentreTranslation source)
   {
      CentreViewModel result = new CentreViewModel();
      result.id = source.Centre.id,
      result.centreTranslationId = source.id,
      result.name = source.Centre.name,
      ....
      result.businessLoungeAbout = source.ProductTranslations
                        .Where(w => w.Product.id == (int)Products.BusinessLounge)
                        .FirstOrDefault().about,
      result.dayOfficeAbout = source.ProductTranslations
                        .Where(w => w.Product.id == (int)Products.DayOffice)
                        .FirstOrDefault().about
      return result;
   }
}

然后您可以重构原来的两种方法,例如:

private IEnumerable<object> CreateCentreViewModelForExport
                                (IQueryable<CentreTranslation> centreTranslation)
{
   return centreTranslation.Select(s => new 
   {
      centreViewModel = CentreViewModel.FromCentreTranslation(s),
      language_group = s.Language.language_group,
      culture = s.Language.cuture
   }
}

private IQueryable<CentreViewModel> CreateCentreViewModel
                                (IQueryable<CentreTranslation> centreTranslation)
{
  return centreTranslation.Select(s => CentreViewModel.FromCentreTranslation(s)),
}

【讨论】:

  • 看起来相当优雅,将这种功能放在 ViewModel 中是否合适?
  • 这是您的电话。你也可以把它放在CentreTranslation 类中并命名为ToCentreViewModel,或者放在另一个映射器类中。
【解决方案3】:
private IQueryable<object> CreateCentreViewModel(IQueryable<CentreTranslation> centreTranslation)
{
    return centreTranslation.Select(s => new 
    {
        model = new CentreViewModel()
        {
             id = s.Centre.id,
             centreTranslationId = s.id,
             name = s.Centre.name,
             [...]
        }
        language_group = s.Language.language_group,
        culture = s.Language.cuture
     }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多