循环迭代器命名约定 [英] Loop iterator naming convention

查看:161
本文介绍了循环迭代器命名约定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道,不知何故,我们在循环中使用 i j 变量。如果需要一个双 for 循环,它很可能会使用如下内容:

We know that, somehow, we use i and j variables in loops very commonly. If one need a double for loop, it's very likely to use something like the following:

for (int i = 0; i < n; i++)
{
    for (int j = 0; j < m; j++)
    {
        // do some stuff...
    }
}

但是,如果我在这些循环中需要第三个 for 循环,我没有第三个迭代器的任何命名约定。我可能使用以下变量: r k ii jj 等......

However, if I need a third for loop in these loops, I don't have any naming convention for the third iterator. I, likely use the following variables: r, k, ii, jj etc...

第三个是否存在命名约定(依此类推...... 。)loop的迭代器?

Is there a naming convention for the third (and so on...) loop's iterator?

推荐答案

对于可读性而言,最重要的是明显的名称

i和j 不是最明显的,但对于简单的情况可能没问题。考虑这个(当然有些不好意思)示例;

The most important thing for readability should be obvious names.
i and j aren't the most obvious, but may be ok for simple cases. Consider this (admittedly somewhat ill thought out) example;

static void Main(string[] args)
{
    for(int i = 0; k < 100; k++)
        for (int j = 0; k < 100; k++)
            for (int k = 0; k < 100; k++)
                Console.WriteLine("" + i + "-" + j + "-" + k);
}

vs

static void Main(string[] args)
{
    for(int survey = 0; survey < 100; survey++)
        for (int question = 0; question < 100; question++)
            for (int option = 0; option < 100; option++)
                Console.WriteLine("" + survey + "-" + question + "-" + option);
}

很容易看出哪个更有意义。但是,虽然我们正在努力,但是如何让它更具可读性,同时更加消除您的命名问题;

It's quite easy to see which makes more sense to read. But while we're at it, how about making it even more readable while eliminating your naming problem even more;

static void Main(string[] args)
{
    for(int survey = 0; survey < 100; survey++)
        PrintSurvey(survey);
}

private static void PrintSurvey(int survey)
{
    for (int question = 0; question < 100; question++)
        PrintQuestion(survey, question);
}

private static void PrintQuestion(int survey, int question)
{
    for (int option = 0; option < 100; option++)
        PrintOption(survey, question, option);
}

private static void PrintOption(int survey, int question, int option)
{
    Console.WriteLine("" + survey + "-" + question + "-" + option);
}

对于这个简单的循环可能过度/冗长,只是想说明一点有多种方法可以处理嵌套循环的命名问题,而不仅仅是找到唯一的名称。

Maybe overkill/verbose for this simple loop, just wanted to make the point that there are more ways you can deal with the naming problem for nested loops than just finding unique names.

这篇关于循环迭代器命名约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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