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

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

问题描述

有时候,我觉得这是比较容易检查是否所有的条件都为真,但只处理了其他的局面。



我想我有时候觉得很容易知道什么是有效的,并承担所有其他情况下是无效的。



例如,让我们说,我们只有真正在乎的时候有什么不对的:

 对象值= GetValueFromSomeAPIOrOtherMethod(); 

如果((值= NULL)及!&安培;!(string.IsNullOrEmpty(value.Prop))及及(possibleValues​​.Contains(value.prop)))
{
//所有条件的通过,但我们实际上并不做任何事情
}
,否则
{
//这里做我的东西,比如错误处理
}

或者我应该改变这种状况是:

 对象值= GetValueFromSomeAPIOrOtherMethod(); 

如果((价值== NULL)||(string.IsNullOrEmpty(value.Prop))||(!possibleValues​​.Contains(value.prop)))
{
//这里做我的东西,比如错误处理
}

或(我觉得这丑陋的):

 对象值= GetValueFromSomeAPIOrOtherMethod(); 

如果(((值= NULL)及!及(string.IsNullOrEmpty(value.Prop))及!及(possibleValues​​.Contains(value.prop))))
{
//难道我的东西在这里,如错误处理
}


解决方案

虽然数量很少对我来说,我有时候觉得以这种形式写作导致某些情况下,清晰的代码。去提供最清晰的形式。编译器不会在意的,应该基本上是生成(可能精确地)相同的代码。



这可能是更清晰,不过,定义分配一个布尔变量在if()语句的条件,然后再编写代码作为变量的否定:

 布尔myCondition =(... ); 
如果(!myCondition)
{

}


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

I guess I sometimes feel that it is easier to know that something is valid, and assume all other cases are not valid.

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.

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'语句中的“其他”部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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