在方法返回的 If-Else 语句中,如果可以隐式遵循 Else,是否应该显式声明 Else? [英] In an If-Else Statement for a method return, should an Else be explicitly stated if it can instead be implicitly followed?

查看:21
本文介绍了在方法返回的 If-Else 语句中,如果可以隐式遵循 Else,是否应该显式声明 Else?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法可以检查某些事情并根据这些检查返回一个布尔值.它涉及一个单独的分支 If 部分,它按顺序检查大约 5 个条件.如果这些条件中的任何一个返回 true,则该方法将 return true;.如果没有一个条件返回真,则该方法将返回假;.由于 If 部分之后的代码仅在所有条件都不为真时才会运行,因此该代码在逻辑上与包含实际 Else 语句相同.

I have a method that checks certain things and returns a Boolean based on those checks. It involves a single branching If section that checks about 5 conditions in sequence. If any of those conditions return true, then the method will return true;. If none of the conditions return true, then the method will return false;. Since the code after the If section will only run if none of the conditions are true, then that code is logically identical to including an actual Else statement.

那么对于这种情况,在 Else 语句中实际写入是否更好?

So is it a better idea to actually write in the Else statement for this kind of situation?

编辑

事实证明,我需要关于哪些条件实际上使其中一些条件变为真"的信息,因此我更改了方法以返回一个 int,其中 -1 表示假"情况.逻辑仍然存在,如果没有一个条件为真,它将返回 -1.所以,我不再有 return (cond1 || cond2 || cond3 || cond4 || cond5); 的可压缩选项,但我也感谢大家的建议,因为我确实没有想到关于它(主要是因为 cond3 是一个非常复杂的条件,涉及检查两对 DateTime 对象的中点的交集,所以它看起来很难看).虽然方法的性质变了,但这个问题的性质没有变化,所有答案仍然基本适用......

It turns out that I needed information on which condition actually tripped the "true" for some of these, so I changed the method to return an int, with -1 representing the "false" situation. The logic still remains, if none of the conditions are true, it'll return -1. So, I no longer have the condensable option of return (cond1 || cond2 || cond3 || cond4 || cond5);, but I thank everyone for that suggestion too, since I had indeed not thought about it (primarily because cond3 is a very complex condition involving checking for intersection in the midpoints of two pairs of DateTime objects, so it would look ugly). While the nature of the method has changed, the nature of this question has not and all answers are still basically applicable...

代码目前是,解释一下并删除所有定义 cond1 到 cond5 的无关代码...

The code is currently, to paraphrase it and cut out all the extraneous code that defines cond1 thru cond5...

if (cond1) { return 1; }
else if (cond2) { return 2; }
else if (cond3) { return 3; }
else if (cond4) { return 4; }
else if (cond5) { return 5; }

推荐答案

与返回硬值相比,我更喜欢这样的事情.

I tend to prefer something like this to returning hard values.

static bool SomeFunc(string arg)
{
    bool result = false;

    if (arg.Length < 10)
    {
        result = true;
    }
    else if (arg.StartsWith("foo"))
    {
        result = true;
    }

    if (!result && arg.EndsWith("foo"))
    {
        result = true;
    }

    return result;
}

这篇关于在方法返回的 If-Else 语句中,如果可以隐式遵循 Else,是否应该显式声明 Else?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆