我更喜欢选项A
bool a, b, c;
if( a && b && c )
{
//This is neat & readable
}
如果您确实有特别长的变量/方法条件,则可以将它们换行
if( VeryLongConditionMethod(a) &&
VeryLongConditionMethod(b) &&
VeryLongConditionMethod(c))
{
//This is still readable
}
如果它们更复杂,那么我会考虑在 if 语句之外单独执行条件方法
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
为每个条件运行单独的函数。
例如
if( a )
{
if( b )
{
}
else
{
//Do Something Else B
}
}
else
{
//Do Something Else A
}