2

我不喜欢这个功能的外观。如果没有“魔术字符串”,有没有办法让它看起来不那么难看。

private static bool Inconsistent(AdStats adStat)   {
  return 
    adStat.Daily.Impressions != adStat.Hourly.Sum(h => h.Value.Impressions) ||
    adStat.Daily.Clicks != adStat.Hourly.Sum(h => h.Value.Clicks) ||
    adStat.Daily.Spent != adStat.Hourly.Sum(h => h.Value.Spent) ||
    adStat.Daily.SocialImpressions != adStat.Hourly.Sum(h => h.Value.SocialImpressions) ||
    adStat.Daily.SocialClicks != adStat.Hourly.Sum(h => h.Value.SocialClicks) ||
    adStat.Daily.SocialSpent != adStat.Hourly.Sum(h => h.Value.SocialSpent) ||
    adStat.Daily.UniqueImpressions != adStat.Hourly.Sum(h => h.Value.UniqueImpressions) ||
    adStat.Daily.UniqueClicks != adStat.Hourly.Sum(h => h.Value.UniqueClicks) ||
    adStat.Daily.SocialUniqueImpressions != adStat.Hourly.Sum(h => h.Value.SocialUniqueImpressions) ||
    adStat.Daily.SocialUniqueClicks != adStat.Hourly.Sum(h => h.Value.SocialUniqueClicks);
}
4

2 回答 2

5

我认为“优化”是指“减少冗余”,也就是不要重复自己

本质上,你有一堆指标。您想检查对于这些指标中的任何一个,该指标的每日广告指标值是否偏离该指标每小时的总和。

一旦你这样想,你可以这样做:

Func<Stat, int>[] metricGetters = 
{
   stat => stat.Impressions,
   stat => stat.Clicks,
   // .. etc. etc.
};

return metricGetters.Any(getter => getter(adStat.Daily) 
                                != adStat.Hourly.Sum(h => getter(h.Value)));
于 2013-06-05T13:45:46.753 回答
1

您可以将 adStat.Hourly.Select(h => h.Value) 提取到变量中,这将减少代码量:

 private static bool Inconsistent(AdStats adStat)
    {
        var hourlyValue = adStat.Hourly.Select(x => x.Value);
        return
          adStat.Daily.Impressions != hourlyValue.Sum(h => h.Impressions) ||
          adStat.Daily.Clicks != hourlyValue.Sum(h => h.Clicks) ||
          adStat.Daily.Spent != hourlyValue.Sum(h => h.Spent) ||
          adStat.Daily.SocialImpressions != hourlyValue.Sum(h => h.SocialImpressions) ||
          adStat.Daily.SocialClicks != hourlyValue.Sum(h => h.SocialClicks) ||
          adStat.Daily.SocialSpent != hourlyValue.Sum(h => h.SocialSpent) ||
          adStat.Daily.UniqueImpressions != hourlyValue.Sum(h => h.UniqueImpressions) ||
          adStat.Daily.UniqueClicks != hourlyValue.Sum(h => h.UniqueClicks) ||
          adStat.Daily.SocialUniqueImpressions != hourlyValue.Sum(h => h.SocialUniqueImpressions) ||
          adStat.Daily.SocialUniqueClicks != hourlyValue.Sum(h => h.SocialUniqueClicks);
    }

我也喜欢 Ani 的想法,它甚至可以从外部注入额外的条件。

于 2013-06-05T13:45:58.007 回答