愚蠢的问题,使用两个单独的 if 子句或一个 if 和 if else 子句是否是一种好习惯,例如:
if (a = 1)
(dosomething)
if (a=2)
(do other thing)
或者
if (a=1)
(do something)
else if (a=2)
(do other thing)
这两个 if 条件不是同时为真。变量 a 用作比较器,根本没有改变。
这两种方式按预期工作,并且在编程上没有任何问题,我只是问什么是好的做法并推荐?
愚蠢的问题,使用两个单独的 if 子句或一个 if 和 if else 子句是否是一种好习惯,例如:
if (a = 1)
(dosomething)
if (a=2)
(do other thing)
或者
if (a=1)
(do something)
else if (a=2)
(do other thing)
这两个 if 条件不是同时为真。变量 a 用作比较器,根本没有改变。
这两种方式按预期工作,并且在编程上没有任何问题,我只是问什么是好的做法并推荐?
取决于你想要达到什么。
在第一种情况下,两个条件都将被评估,因为它们是独立的——即使两个条件都是true。
在第二种情况下,如果第一个条件被评估为true,则将跳过else-if分支。
你可以在JLS上看到完整的解释。
如果您使用第一种方式,则会检查每个 if 语句。在第二种方式中,如果一个是正确的,则忽略以下所有其他情况。
因此,如果存在复杂的 if 条件,则方式 1 可能需要更长的时间。
通过检查这些值(a == 1、a == 2、a == 3、...),尝试切换!
这两个测试明显不同。在第一种情况下,如果 firsta
是 1 并且do something
将 value 更改a
为 2, thendo other thing
也会被执行。在第二个变体中不是这种情况。因此,使用哪一个取决于您想要实现的目标。
这取决于你的意思。如果您希望仅在第一个条件不成立时才测试第二个条件,请使用if (...) else if (...)
选项。相反,如果您希望独立检查这两个条件,请使用if (...) if (...)
.
一个人不能谈论两件事之间的最佳实践,这意味着不同的事情。只需在每种情况下编写您设计的算法告诉您编写的内容,即忠实地在代码中表达您的设计。
如果条件互斥(同一时间只能有一个),第二种方式。否则,如果两种情况可以同时发生,则第一种方式是正确的。
我会使用更容易阅读的样式。
清晰总是比难以遵循的代码要好。
执行速度在这里不会是一个大问题。
至少在 Java 字节码中,存在三种不同的场景:
if(a == 3) // load an int from local variable a, load int value 3 onto the stack
// if they are not equal go (branch) to line a = 4;
a = 5; // load int value 5 onto the stack, save it into the variable
else // there's no instruction for this line as it's behavior was
// described in line if(a == 3)
a = 4; // load int value 4 onto the stack, save it into the variable
if(a == 3) // load an int from local variable a, load int value 3 onto the
// stack, if they are not equal go (branch) to line if(a != 3)
a = 5; // load int value 5 onto the stack, save it into the variable
// go to line after a = 4;
else if(a != 3) // load an int from local variable a, load int value 3 onto the
// stack, if they are equal go (branch) to line after a = 4;
a = 4; // load int value 4 onto the stack, save it into the variable
if(a == 3) // load an int from local variable a, load int value 3 onto the stack
// if they are not equal go (branch) to line if(a != 3)
a = 5; // load int value 5 onto the stack, save it into the variable
if(a != 3) // load an int from local variable a, load int value 3 onto the stack
// if they are equal go (branch) to line after a = 4;
a = 4; // load int value 4 onto the stack, save it into the variable
int a = 5;
int ifelse()
{
if(a == 5) a = 3; // true, go to return
else a = 6;
return a; // returns 3
}
int ifelseif()
{
if(a == 2) a = 3; // false, go to next line
else if(a == 3) a = 6; // false, go to next line
else if(a == 5) a = 9; // true go to return
return a; // returns 9 (btw you might use switch for this)
}
int ifif()
{
if(a == 5) a = 3; // true, go to next line
if(a == 3) a = 6; // true, go to return
return a; // returns 6
}