为什么“用循环索引猴子"不好? [英] Why is it bad to "monkey with the loop index"?

查看:66
本文介绍了为什么“用循环索引猴子"不好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

史蒂夫·麦康奈尔(Steve McConnell)的清单项目之一是您不应胡闹循环索引(第25页第16章,<循环索引>,,PDF格式).

One of Steve McConnell's checklist items is that you should not monkey with the loop index (Chapter 16, page 25, Loop Indexes, PDF format).

这很直观,是我一直遵循的一种做法,除了可能是因为我学会了如何编程.

This makes intuitive sense and is a practice I've always followed except maybe as I learned how to program back in the day.

在最近的代码审查中,我发现此尴尬的循环并将其立即标记为可疑.

In a recent code review I found this awkward loop and immediately flagged it as suspect.

        for ( int i=0 ; i < this.MyControl.TabPages.Count ; i++ )
        {
            this.MyControl.TabPages.Remove ( this.MyControl.TabPages[i] );
            i--;
        }

这几乎很有趣,因为它设法通过将索引保持为零直到删除所有TabPage来工作.

It's almost amusing since it manages to work by keeping the index at zero until all TabPages are removed.

该循环本可以写为

        while(MyControl.TabPages.Count > 0)
            MyControl.TabPages.RemoveAt(0);

由于控件实际上是在与循环大约相同的时间编写的,因此它甚至可能被编写为

And since the control was in fact written at about the same time as the loop it could even have been written as

        MyControl.TabPages.Clear();

此后,我在代码审查问题上受到挑战,发现我对为什么这是一种不好的做法的表述没有我想要的那么强烈.我说过,很难理解循环的流程,因此很难维护和调试,并且最终在代码的生命周期内会更加昂贵.

I've since been challenged about the code-review issue and found that my articulation of why it is bad practice was not as strong as I'd have liked. I said it was harder to understand the flow of the loop and therefore harder to maintain and debug and ultimately more expensive over the lifetime of the code.

对于这是不好的做法,是否有更好的表述?

Is there a better articulation of why this is bad practice?

推荐答案

我认为您的口才很好.也许可以这样写:

I think your articulation is great. Maybe it can be worded like so:

由于逻辑可以表达得很多 更清晰,应该如此.

Since the logic can be expressed much clearer, it should.

这篇关于为什么“用循环索引猴子"不好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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