循环中的最后一个元素是否应该单独处理? [英] Does the last element in a loop deserve a separate treatment?

查看:182
本文介绍了循环中的最后一个元素是否应该单独处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  i = begin 
while(i!=结束){
// ...做东西
if(i == end-1(one-but-last element)){
...做其他的东西
}
增量i
}

然后我问这个问题:写这个?

  i = begin 
mid =(end - begin)/ 2 //(中间元素)
while(i!= end){
// ...做东西
if(i> mid){
...做其他的东西
}
增量i
}

在我看来,这打击了写作的意图一个循环:循环,因为每个元素都有一些共同点。使用这个构造,对于你做一些不同的元素。所以,我得出结论,你需要一个单独的循环为这些元素:

$ p $ code i =开始)/ 2 //(中间元素)
while(i!= mid){
// ...做东西
增量i
}

while(i!= end){
// ...做东西
// ...做其他的东西
增量的i
}

现在我甚至看到了问题关于如何编写如果 - 条款以一个很好的方式...我伤心:这里不对。



我错了吗?如果是这样的话,那么在编码的时候,你会发现什么是特殊情况下的混乱循环体呢?

> @xtofl,

我同意你的关注。百万倍我碰到过类似的问题。



任何一个开发人员都会为第一个元素或最后一个元素添加特殊处理。

在大多数情况下,值得从 startIdx + 1 或者 endIdx - 1 元素循环,甚至将一个长循环拆分成多个较短的循环。



在我看来,不常见的 / em>只要有可能就应该在循环之外处理。


When reviewing, I sometimes encounter this kind of loop:

i = begin
while ( i != end ) {    
   // ... do stuff
   if ( i == end-1 (the one-but-last element) ) {
      ... do other stuff
   }
   increment i
}

Then I ask the question: would you write this?

i = begin
mid = ( end - begin ) / 2 // (the middle element)
while ( i != end ) {    
   // ... do stuff
   if ( i > mid ) {
      ... do other stuff
   }
   increment i
}

In my opinion, this beats the intention of writing a loop: you loop because there is something common to be done for each of the elements. Using this construct, for some of the elements you do something different. So, I conclude, you need a separate loop for those elements:

i = begin
mid = ( end - begin ) / 2 //(the middle element)
while ( i != mid ) {    
   // ... do stuff
   increment i
}

while ( i != end ) {
   // ... do stuff
   // ... do other stuff
   increment i
}

Now I even saw a question on SO on how to write the if-clause in a nice way... And I got sad: something isn't right here.

Am I wrong? If so, what's so good about cluttering the loop body with special cases, which you are aware of upfront, at coding time?

解决方案

@xtofl,

I agree with your concern.

Million times I encountered similar problem.

Either developer adds special handling for first or for last element.

In most cases it is worth to just loop from startIdx + 1 or to endIdx - 1 element or even split one long loop into multiple shorter loops.

In a very rare cases it's not possible to split loop.

In my opinion uncommon things should be handled outside of the loop whenever possible.

这篇关于循环中的最后一个元素是否应该单独处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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