我应该期望看到`for`循环中的计数器在其内部发生了变化吗? [英] Should I expect to see the counter in `for` loop changed inside its body?

查看:203
本文介绍了我应该期望看到`for`循环中的计数器在其内部发生了变化吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读别人的代码,他们分别在循环内增加for循环计数器,还包括通常的事后考虑。例如:

  for(int y = 4; y <12; y ++){
// blah
if(var y ++;

$ $



$基于大多数其他人已经写和读过的代码,我应该期待看到这个?

解决方案

for 循环并不十分普遍。这会让很多人阅读这些代码感到惊讶。 您的读者很少是一个好主意。



循环计数器的附加操作增加了一个代码的复杂性,因为您必须记住它的含义以及它如何影响循环的整体行为。就像Arkady提到的那样,这会让你的代码难以维护。

简单来说,避免这种模式。当你遵循干净的代码原则,特别是单层抽象(SLA)原则时, (b)

  for(something)
if(somethingElse)
y ++

遵循这个原则要求您将如果块移入它自己的方法,使得在该方法内操纵一些外部计数器很尴尬。



但是,除此之外,可能会出现像你的例子那样的某些东西但是对于这些情况,为什么不使用 while 循环呢?

换句话说:让你的例子变得复杂和令人困惑的是事实上两个不同部分的代码会改变你的循环计数器。所以另一种方法可能是这样的:

$ p $ while(y< whatever){
...
y =确定(y,谁知道);





$ b

然后,这个新方法可以成为计算如何更新循环的核心变量。


I'm reading someone else's code and they separately increment their for loop counter inside the loop, as well as including the usual afterthought. For example:

for( int y = 4; y < 12; y++ ) {
    // blah
    if( var < othervar ) {
        y++;
    }
    // blah
}

Based on the majority of code others have written and read, should I be expecting to see this?

解决方案

The practice of manipulating the loop counter within a for loop is not exactly widespread. It would surprise many of the people reading that code. And surprising your readers is rarely a good idea.

The additional manipulation of your loop counter adds a ton of complexity to your code because you have to keep in mind what it means and how it affects the overall behavior of the loop. As Arkady mentioned, it makes your code much harder to maintain.

To put it simply, avoid this pattern. When you follow "clean code" principles, especially the single layer of abstraction (SLA) principle, there is no such thing as

for(something)
  if (somethingElse)
   y++

Following the principle requires you to move that if block into its own method, making it awkward to manipulate some outer counter within that method.

But beyond that, there might be situations where "something" like your example makes; but for those cases - why not use a while loop then?

In other words: the thing that makes your example complicated and confusing is the fact that two different parts of the code change your loop counter. So another approach could look like:

 while (y < whatever) {
   ...
   y = determineY(y, who, knows);
 }

That new method could then be the central place to figure how to update the loop variable.

这篇关于我应该期望看到`for`循环中的计数器在其内部发生了变化吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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