new*_*own 5 if-statement coding-style
我经常要这样做,
if(condition1) {
if {condition2) { //this condition is repeated again below
//dosomething here 1 code 1
}
else{
//dosomething here 2 code 2
}
}
else {
if {condition2) { //same if condition as above
//dosomething here 3 code 3
}
else{
//dosomething here 4 code 4
}
}
Run Code Online (Sandbox Code Playgroud)
基本上,在两种情况下只检查if(condition2)是否重复,并且dosomething在所有4个位置都不同,即code1,code2,code3,code4都是不同的代码.
那么,无论如何要使它紧凑和可读或者这很好吗?
谢谢.
在完成编辑并查看答案之后,我现在想知道这个问题是否有意义.我现在觉得很蠢.
对于您的具体情况,最好的选择是:
不再适用 - 适用于此处的dosomething 1与此处的dosomething相同的情况3
if ( c2 )
{
}
else if ( c1 )
{
}
else
{
}
Run Code Online (Sandbox Code Playgroud)
对于不太简单的情况,您可以将条件组合在一起:
if ( c1 && c2 )
{
}
else if ( c1 && !c2 )
{
}
else if ( !c1 && c2 )
{
}
else if ( !c1 && !c2 )
{
}
Run Code Online (Sandbox Code Playgroud)
虽然我不知道这是否更具可读性.
如果需要更多条件,我看到这样的代码:
do {
if (c1)
{
//....
break;
}
if (c2)
{
//....
break;
}
//.....
} while (false);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
113 次 |
| 最近记录: |