为什么在循环内继续是一个坏主意?
Douglas Crockfod 表示,通常最好重构循环内的 continue
。
为什么循环中的 continue 被认为是不好的?
Douglas Crockfod says that it is usually better to refactor the continue
inside the loop.
Why is continue considered bad within a loop?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
continue
意味着您在while
中编写的条件不充分。您应该在
while
循环中使用if
,或者将条件添加到while
循环中。The use of
continue
would mean that you have insufficient conditions written in yourwhile
.You should instead use
if
inside yourwhile
loop, or add the condition into thewhile
loop.在循环体内使用 goto、break、 continue、 throw 或 return 也可能会产生不良效果。这是循环控制和循环体紧密交织的另一个示例。还像以前一样写1、2、3吗?你确定吗?
您可能会认为建议您不要在循环体内使用 return 语句过于热心了。我真的是这个意思吗?是的,我愿意。返回某些内容的函数应该通过函数末尾的单个 return 语句来完成。以下是一些实际原因:
链接
免责声明:不是我的材料,我已引用回到源头
Using goto, break, continue, throw, or return inside the loop body can all have the un-desired effect as well. Here's another example where the loop control and the loop body are tightly interwoven. Does it write 1, 2, and 3 as before? Are you sure?
You might be thinking that advising you not to use return statements inside loop bodies is over zealous. Do I really mean that? Yes I do. Functions that return something should do so via a single return statement at the very end of the function. Here are some practical reasons why:
Link
Disclaimer: Not my material, I have referenced back to the source
Continue
的效果在某种程度上类似于转到循环开头的goto
。因此,它使您的代码更难以理解 - 就像goto
一样。The effect of
continue
is somehow comparable to agoto
to the begin of the loop. It therefore makes your code more difficult to understand - likegoto
s.