【发布时间】:2015-01-30 14:06:51
【问题描述】:
我有一系列略显笨拙的 if 语句,我习惯性地嵌套如下:
// Cannot collide with right
if(direction.x < 0)
{
// Cannot collide with top
if(direction.y < 0)
{
// Check left and bottom
}
// Cannot collide with bottom
else if (direction.y > 0)
{
// Check left and top
}
// Cannot collide with top or bottom
else
{
// Check left only
}
}
// Cannot collide with left
else if (direction.x > 0)
{
// Cannot collide with top
if(direction.y < 0)
{
// Check right and bottom
}
// Cannot collide with bottom
else if (direction.y > 0)
{
// Check right and top
}
// Cannot collide with top or bottom
else
{
// Check right only
}
}
但是我发现它有点难以阅读,并认为它可能更容易理解为一组扁平的 if 语句,有点像 switch:
// Cannot collide with right or top
if(direction.x < 0 && direction.y < 0)
{
// Check left and bottom
}
// Cannot collide with right or bottom
else if(direction.x < 0 && direction.y > 0)
{
// Check left and top
}
// Cannot collide with right, top or bottom
else if(direction.x < 0)
{
// Check left only
}
// Cannot collide with left or top
else if (direction.x > 0 && direction.y < 0)
{
// Check right and bottom
}
// Cannot collide with left or bottom
else if (direction.x > 0 && direction.y > 0)
{
// Check right and top
}
// Cannot collide with left, top or bottom
else
{
// Check right only
}
这样做的明显缺点是我要多次重新检查一个条件。在这种情况下,它是如此之小,我无法想象它有什么不同,但我的问题是:
- 用于 C#、Java 等的现代编译器是否可以优化第二个示例以删除重复检查? 在此示例中这很好,但如果条件检查也有副作用,则可能会导致问题。
- 一般来说,哪种方法更受欢迎?
【问题讨论】:
-
你的第二个例子并没有以任何方式展平,如果添加一个新的嵌套层,因为它相当于
else { if(predicate) { ...,你就不需要{。 -
我认为单独阅读您的代码 cmets 表明应该首选哪种方式
-
最好尽可能避免嵌套 if 语句。当我们有深层嵌套的 if 语句时,代码变得难以阅读。不建议使用 PMD 工具。
标签: java c# if-statement optimization compilation