Sai*_*ait 4 iterator loops naming-conventions
我们知道,不知何故,我们在循环中使用i和j变量非常常见.如果需要双for循环,则很可能使用如下内容:
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
// do some stuff...
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我需要for在这些循环中使用第三个循环,我没有第三个迭代器的任何命名约定.我,会使用以下变量:r,k,ii,jj等...
是否存在第三个(等等......)循环迭代器的命名约定?
可读性最重要的事情应该是明显的名称.
i和j不是最明显的,但对于简单的情况可能没问题.考虑一下这个(不可否认的有点想法)的例子;
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);
}
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
很容易看出哪个更有意义.但是,虽然我们正在努力,但是如何让它更具可读性,同时更加消除您的命名问题;
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);
}
Run Code Online (Sandbox Code Playgroud)
对于这个简单的循环可能有点过分/冗长,只是想说明有更多方法可以处理嵌套循环的命名问题,而不仅仅是找到唯一的名称.