Jos*_*osh 9 c++ java loops coding-style
说我有这样的循环:
for (int i = 0; i < someint; i++)
{
if (i == somecondition)
{
DoSomething();
continue;
}
doSomeOtherStuff();
}
Run Code Online (Sandbox Code Playgroud)
与...
for (int i = 0; i < someint; i++)
{
if (i == somecondition)
{
DoSomething();
}
else
{
doSomeOtherStuff();
}
}
Run Code Online (Sandbox Code Playgroud)
有没有理由使用一个而不是另一个?或者只是个人偏好?
我要求的主要语言是Java,但我想它也适用于大多数其他语言.
我更喜欢第二种结构......
for (int i = 0; i < someint; i++)
{
if (i == somecondition)
{
DoSomething();
//lets say lot of code
//..
//...
//...
//...
continue;
}
else
{
doSomeOtherStuff();
}
}
Run Code Online (Sandbox Code Playgroud)
让我们说你之前有很多代码continue
.通过观察,它立即显而易见
else
{
doSomeOtherStuff();
}
Run Code Online (Sandbox Code Playgroud)
它没有无条件执行.
对我来说,这取决于分支then
和else
分支相对大小之间的分歧:如果一个大于另一个,而较小的一个代表逻辑上的异常情况,我将较短的一个放入then
,并添加一个continue
; 当他们大致相等,无论在规模和逻辑流,我让他们在自己then
和else
分支机构.
for (String tok : tokens) {
if (isKeyword(tok)) {
output.write(tok);
continue;
}
// Do some massive processing of non-keyword tokens here
// This block goes on...
// and on...
// and on... You get the idea
}
Run Code Online (Sandbox Code Playgroud)
与
for (String op : operators) {
if (isAdditive(op)) {
// Do something for additive ops
} else {
// Do something for non-additive ops
}
}
Run Code Online (Sandbox Code Playgroud)