格式化具有多个条件的语句的最佳方法 [英] Best way to format if statement with multiple conditions
问题描述
如果你想根据两个或多个条件执行某些代码,这是格式化if语句的最佳方法吗?
If you want to some code to execute based on two or more conditions which is the best way to format that if statement ?
第一个例子: -
if(ConditionOne && ConditionTwo && ConditionThree)
{
Code to execute
}
第二个例子: -
if(ConditionOne)
{
if(ConditionTwo )
{
if(ConditionThree)
{
Code to execute
}
}
}
这是最容易理解的并且请记住,每个条件可能是一个很长的函数名称。
which is easiest to understand and read bearing in mind that each condition may be a long function name or something.
推荐答案
我更喜欢选项A
bool a, b, c;
if( a && b && c )
{
//This is neat & readable
}
如果确实有特别长的变量/方法条件,你可以直接断行它们
If you do have particularly long variables/method conditions you can just line break them
if( VeryLongConditionMethod(a) &&
VeryLongConditionMethod(b) &&
VeryLongConditionMethod(c))
{
//This is still readable
}
如果它们更复杂,那么我会考虑在if语句之外单独执行条件方法
If they're even more complicated, then I'd consider doing the condition methods separately outside the if statement
bool aa = FirstVeryLongConditionMethod(a) && SecondVeryLongConditionMethod(a);
bool bb = FirstVeryLongConditionMethod(b) && SecondVeryLongConditionMethod(b);
bool cc = FirstVeryLongConditionMethod(c) && SecondVeryLongConditionMethod(c);
if( aa && bb && cc)
{
//This is again neat & readable
//although you probably need to sanity check your method names ;)
}
恕我直言选项'B'的唯一原因是如果你有单独的 else
函数来运行每个条件。
IMHO The only reason for option 'B' would be if you have separate else
functions to run for each condition.
例如
if( a )
{
if( b )
{
}
else
{
//Do Something Else B
}
}
else
{
//Do Something Else A
}
这篇关于格式化具有多个条件的语句的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!