c# - 是否有一种更易读的方式来制作一长串 && 语句?

标签 c# design-patterns if-statement code-readability

假设我有一个长而复杂的条件列表,这些条件必须为真才能运行 if 语句。

if(this == that && foo != bar && foo != that && pins != needles && apples != oranges)
{
    DoSomethingInteresting();
}

通常,如果我被迫做这样的事情,我会把每条语句放在自己的行上,如下所示:

if
(
         this == that 
    &&    foo != bar 
    &&    foo != that 
    &&   pins != needles 
    && apples != oranges
)
{
    DoSomethingInteresting();
}

但我还是觉得这有点乱。我很想像这样将 if 语句的内容重构到它自己的属性中

if(canDoSomethingInteresting)
{
    DoSomethingInteresting();
}

但是这只是将所有困惑转移到 canDoSomethingInteresting() 中,并没有真正解决问题。

正如我所说,我的 goto 解决方案是中间的,因为它不会像最后一个那样混淆逻辑并且比第一个更具可读性。但必须有更好的方法!

响应 Sylon 评论的示例

bool canDoSomethingInteresting
{
    get{
        //If these were real values, we could be more descriptive ;)
        bool thisIsThat = this == that;
        bool fooIsntBar = foo != bar;
        bool fooIsntThat = foo != that;
        return 
        (
               thisIsThat
            && fooIsntBar
            && fooIsntThat
        );
    }
}
if(canDoSomethingInteresting)
{
    DoSomethingInteresting();
}

最佳答案

在我看来,将困惑转移到属性或方法中并不是一个坏主意。这样它是独立的,并且您执行 if(..) 检查的主要逻辑变得更具可读性。特别是如果要检查的条件列表很大,最好是在一个属性中,这样如果你需要重新使用你就不会重复该检查。

if(IsAllowed)
{
   DoSomethingInteresting();
}

关于c# - 是否有一种更易读的方式来制作一长串 && 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14208721/

相关文章:

c# - 后面的代码不从下拉列表中获取当前文本

reactjs - Ant Design + React-table。如何在 Ant Design 提供的 UI 元素之上构建 react-table 的过滤能力?

javascript - 基于状态的函数执行无法正常工作

php - Laravel 上的存储库模式

java - 在java中将多个if语句组合为一个输入

swift - Bool 未正确返回

c# - Elasticsearch.net NEST Bool查询未生成预期的请求

c# - 使用 ASP .NET Core 2.0 从 Main 访问服务

c# - MVVM跨WPF区域实现

java - 如何创建具有根据唯一键生成的属性的对象