Buc*_*Guy 12 coding-style nested
在代码审查期间,一位资深开发人员评论了我在代码中进行的一些嵌套.他建议我设置一个bool值,这样我就不会有多个嵌套级别.我认为我的代码更具可读性,但希望得到其他开发者的意见.哪个风格更好?他的下意识是否厌恶筑巢?
下面是一些简化的代码示例.
嵌套:
If(condition1)
{
If(condition2)
{
if(condition3)
{
return true;
}
else
{
log("condition3 failed");
}
else
{
log("condition2 failed")
}
}
else
{
log("condition1 failed")
}
return false;
Run Code Online (Sandbox Code Playgroud)
要么
Bool驱动:
bool bRC = false;
bRC = (condition1);
if(brc)
{
bRC = (condition2);
}
else
{
log("condition1 failed");
return false;
}
if(bRC)
{
bRC = (condition3);
}
else
{
log("condition2 failed");
return false;
}
if(bRC)
{
return true;
}
else
{
log("condition3 failed");
return false;
}
Run Code Online (Sandbox Code Playgroud)
tva*_*son 32
我更喜欢你,但我可能做的事情如下:
if (condition1 && condition2 && condition3)
{
return true;
}
else if (!condition1)
{
log("condition1 failed");
}
else if (!condition2)
{
log("condition2 failed");
}
else
{
log("condition3 failed");
}
return false;
Run Code Online (Sandbox Code Playgroud)
如果条件是复杂的表达式,那么我可以在评估if语句之前将表达式分配给适当命名的变量,以避免重新计算每个if中的值.
这假设正常模式是所有条件都为真,因此您希望首先进行检查.如果正常模式是一个或多个条件为假,那么我会重新排序并依次检查每个否定,如果所有检查都失败则返回true.这也将消除临时变量取代复杂表达式的需要.
Chr*_*utz 19
如果你没有关于多个返回点的任何愚蠢规则,我认为这是非常好的(其他人也是如此,但他们因未知原因删除了他们的答案):
if(!condition1)
{
log("condition1 failed");
return false;
}
if(!condition2)
{
log("condition2 failed");
return false;
}
if(!condition3)
{
log("condition3 failed");
return false;
}
return true;
Run Code Online (Sandbox Code Playgroud)
也许这是对超级嵌套的一种平等的下意识厌恶,但它肯定比他在某些值中存储布尔条件的垃圾更清晰.但是,它在上下文中可能不太可读:考虑其中一个条件是什么isreadable().更清楚地说,if(isreadable())因为我们想知道某些东西是否可读.if(!isreadable())建议我们是否想知道它是否不可读,这不是我们的意图.当然有可能存在一个比另一个更可读/更直观的情况,但我自己也是这种方式的粉丝.如果有人挂断了退货,你可以这样做:
if(!condition1)
log("condition1 failed");
else if(!condition2)
log("condition2 failed");
else if(!condition3)
log("condition3 failed");
else
return true;
return false;
Run Code Online (Sandbox Code Playgroud)
但在我看来,这是相当卑鄙的,而且不太"清晰".
Mic*_*and 18
我个人觉得嵌套代码更容易阅读.
与嵌套版本类似,但对我来说更清洁:
if not condition1:
log("condition 1 failed")
else if not condition2:
log("condition 2 failed")
else if not condition3:
log("condition 3 failed")
else
return true;
return false;
Run Code Online (Sandbox Code Playgroud)
请注意每个条件都要评估一次.
| 归档时间: |
|
| 查看次数: |
1040 次 |
| 最近记录: |