【问题标题】:More elegant way of handling this logic处理这种逻辑的更优雅的方式
【发布时间】:2012-08-14 08:59:59
【问题描述】:
private bool SearchFilter(object sender)
{
    CommDGDataSource item = sender as CommDGDataSource;
    if (FilterPropertyList.IsErrorFilter)
    {
        if (!item.Error)
            return false;
    }
    if (FilterPropertyList.IsDestinationFilter)
    {
        if (!(item.Destination == FilterPropertyList.Destination))
            return false;
    }
    if (FilterPropertyList.IsSourceFilter)
    {
        if (!(item.Source == FilterPropertyList.Source))
            return false;
    }

    return true;
}

上面的代码运行良好,但我想知道是否有更优雅的方式来编写上面的代码。

【问题讨论】:

  • 我只会将! 用于原子语句,在这种情况下!= 会为您省去括号...
  • 你也可以对外部 if 结构使用 switch 语句
  • 过滤器可以同时处理多个事物吗?例如。可以是ErrorFilterSourceFilter吗?
  • @djery: 使用switch 会改变方法的逻辑。
  • 你能给FilterPropertyList更多的代码吗?

标签: c# .net if-statement logic


【解决方案1】:

你可以通过如下的小改动来提高可读性

private bool SearchFilter(object sender)
{
    CommDGDataSource item = sender as CommDGDataSource;

    if (FilterPropertyList.IsErrorFilter && !item.Error)
        return false;

    if (FilterPropertyList.IsDestinationFilter && item.Destination != FilterPropertyList.Destination)
        return false;

    if (FilterPropertyList.IsSourceFilter && item.Source != FilterPropertyList.Source)
        return false;

    return true;
}

【讨论】:

  • 这是否更具可读性取决于您的显示器的宽度......但我认为它应该适合大多数人。
  • 这大概就是我要写的。我知道有些人更喜欢用return 替换最后一个if,而不是使用额外的尾随return,但我更喜欢这个,因为它使以后修改过滤器变得更容易和更清晰。
  • 唯一的缺点是你不能粘贴任何额外的逻辑,如果只有第一个条件为真
【解决方案2】:

我不认为弄乱布尔表达式有什么好处,除了我的comment 中提到的简单修改。如果你最终得到丑陋的代码,你的设计就不是那么好。

在这种情况下,您可能可以通过以下方式重构职责:

  • 创建过滤器列表对象
  • 在这些对象中实现逻辑

类似这样的伪代码:

foreach (var filter in filters)
    if !filter.Filter(item) return false;
return true;
public interface IFilter
{
    bool Filter(CommDGDataSource item);
}

public class ErrorFilter : IFilter
{
    public bool Filter(CommDGDataSource item)
    {
        return item.Error;
    }
}

public class DestinationFilter : IFilter
{
    public string Destination { get; set; }

    public bool Filter(CommDGDataSource item)
    {
        return item.Destination == Destination;
    }
}

//etc..

【讨论】:

    猜你喜欢
    • 2019-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-10
    相关资源
    最近更新 更多