只使用“if-else"语句的“else"部分是否可以接受? [英] Is it acceptable to only use the 'else' portion of an 'if-else' statement?

查看:38
本文介绍了只使用“if-else"语句的“else"部分是否可以接受?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时,我觉得检查所有条件是否为真更容易,但只处理其他"情况.

Sometimes, I feel like it is easier to check if all of the conditions are true, but then only handle the "other" situation.

我想我有时觉得更容易知道某事是有效的,并假设所有其他情况都是无效的.

例如,假设我们只有在出现问题时才真正关心:

For example, let's say that we only really care about when there is something wrong:

object value = GetValueFromSomeAPIOrOtherMethod();

if((value != null) && (!string.IsNullOrEmpty(value.Prop)) && (possibleValues.Contains(value.prop)))
{
    // All the conditions passed, but we don't actually do anything
}
else
{
    // Do my stuff here, like error handling
}

或者我应该将其更改为:

Or should I just change that to be:

object value = GetValueFromSomeAPIOrOtherMethod();

if((value == null) || (string.IsNullOrEmpty(value.Prop)) || (!possibleValues.Contains(value.prop)))
{
    // Do my stuff here, like error handling
}

或者(我觉得很难看):

Or (which I find ugly):

object value = GetValueFromSomeAPIOrOtherMethod();

if(!((value != null) && (!string.IsNullOrEmpty(value.Prop)) && (possibleValues.Contains(value.prop))))
{
    // Do my stuff here, like error handling
}

推荐答案

虽然对我来说很少见,但有时我觉得在某些情况下以这种形式编写会导致最清晰的代码.选择最清晰的形式.编译器不会在意,应该生成基本(可能完全)相同的代码.

Though rare for me, I sometimes feel that writing in this form leads to the clearest code in some cases. Go for the form that provides the most clarity. The compiler won't care, and should generate essentially (probably exactly) the same code.

不过,在 if () 语句中定义一个分配条件的布尔变量可能更清楚,然后将代码编写为该变量的否定:

It may be clearer, though, to define a boolean variable that is assigned the condition in the if () statement, then write your code as a negation of that variable:

bool myCondition = (....);
if (!myCondition)
{
    ...
}

这篇关于只使用“if-else"语句的“else"部分是否可以接受?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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