测试循环是在顶部还是在底部? (一会儿vs一会儿做)

编程入门 行业动态 更新时间:2024-10-26 19:28:21
本文介绍了测试循环是在顶部还是在底部? (一会儿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一会儿做)

本文发布于:2023-05-31 10:08:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/389596.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:是在   会儿   测试

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!