测试循环是在顶部还是在底部? (一会儿vs一会儿做) [英] Test loops at the top or bottom? (while vs. do while)

查看:81
本文介绍了测试循环是在顶部还是在底部? (一会儿vs一会儿做)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在大学(80年代中期)上CS时,不断重复的想法之一就是总是编写循环,循环在顶部(while)而不是底部(do ... while)进行测试. )的循环.这些概念经常以研究为依据,这些研究表明,在顶部进行测试的循环比在底部进行测试的循环在统计学上更可能是正确的.

When I was taking CS in college (mid 80's), one of the ideas that was constantly repeated was to always write loops which test at the top (while...) rather than at the bottom (do ... while) of the loop. These notions were often backed up with references to studies which showed that loops which tested at the top were statistically much more likely to be correct than their bottom-testing counterparts.

结果,我几乎总是写在最上面测试的循环.如果它在代码中引入了额外的复杂性,我不会这样做,但是这种情况似乎很少.我注意到有些程序员倾向于几乎完全编写在底部进行测试的循环.当我看到类似以下的构造:

As a result, I almost always write loops which test at the top. I don't do it if it introduces extra complexity in the code, but that case seems rare. I notice that some programmers tend to almost exclusively write loops that test at the bottom. When I see constructs like:

if (condition)
{
    do
    {
       ...
    } while (same condition);
}

或反数(while内的if),这使我想知道他们是否实际上是这样写的,或者当他们意识到循环无法处理空值情况时是否添加了if语句.

or the inverse (if inside the while), it makes me wonder if they actually wrote it that way or if they added the if statement when they realized the loop didn't handle the null case.

我已经进行了一些谷歌搜索,但是没有找到有关此主题的任何文献.你们(和女孩)如何编写循环?

I've done some googling, but haven't been able to find any literature on this subject. How do you guys (and gals) write your loops?

推荐答案

我始终遵循以下规则:如果应该运行零次或多次,请在开始时进行测试,是否必须运行一次 或更多,最后测试.我看不到使用您在示例中列出的代码的任何逻辑原因.它只会增加复杂性.

I always follow the rule that if it should run zero or more times, test at the beginning, if it must run once or more, test at the end. I do not see any logical reason to use the code you listed in your example. It only adds complexity.

这篇关于测试循环是在顶部还是在底部? (一会儿vs一会儿做)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆