问题描述
如果您想根据两个或多个条件执行某些代码,那么格式化 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
}
这篇关于格式化具有多个条件的 if 语句的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!