您有什么秘诀来跟踪和避免循环中的错误? [英] What are your tips for keeping track and avoiding bugs in loops?
本文介绍了您有什么秘诀来跟踪和避免循环中的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我刚刚发现...再次出现...实时浪费错误,如下所示
I just found ... AGAIN ... a real time wastage bug as follows
for (int i = 0; i < length; i++)
{ //...Lots of code
for (int j = 0; i < length; j++)
{
//...Lots of code
}
}
您是否注意到前方应该是j的内部i?我也没有.所以从现在开始,我将使用:
Did you notice straight ahead the inner i which SHOULD BE j ? Neither did I. So from now on I am going to use:
for (int i = 0; i < length; i++)
{
for (int i1 = 0; i1 < length; i1++)
{
}
}
您对内部和外部while和循环有何建议?
What are your tips for inner and outer while and for loops ?
感谢您的宝贵意见.随函附上建议技巧的简短摘要:
Thanks for the valuable responses. Herewith short summary of the proposed tips:
- 为索引变量使用有意义的变量名称(相反,我使用SomeObjCollectionLength)
- 将内部循环的内容放入一个单独的方法中,然后从外部循环调用该方法
- 内外循环之间的代码行数量难以管理,这是发出代码气味的强烈信号
- 避免复制和粘贴,应小心地编写索引vars
您可能希望通过 LBushkin 查看摘要以获取
You might want to check the summary by LBushkin for the following
- 尽可能使用foreach和迭代器
- 在进入循环之前初始化变量
- 使每个循环仅执行一个功能.避免将责任混为一谈
- 在可能的情况下,使循环足够短以一次查看所有内容
推荐答案
请勿使用i& j(或任何其他单字母变量)作为索引名称.使用适当的名称,您将不会遇到此类问题.
Don't use i & j (or any other single letter variable) as index names. Use proper names and you will not get into this type of problems.
这篇关于您有什么秘诀来跟踪和避免循环中的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文