For 循环构造和代码复杂度

发布于 2024-08-04 08:43:51 字数 1431 浏览 5 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

寒尘 2024-08-11 08:43:51

我实际上敢建议在这种情况下考虑使用 GOTO 来打破循环:

   for (size_t x = 0; x < LIMIT && !found; ++x) {
      if (something) 
          goto found;

      else {
          ...
      }
    }

    // not found
           ...

      return;

    found:

       ...
      return;

我认为这种形式既简洁又可读。它在许多简单的情况下可能会有一些好处(例如,当这个函数中没有通用处理时,在找到/未找到的情况下)。

关于 goto 收到的一般皱眉,我发现这是对 的常见误解Dijkstra 最初的主张:他的论点支持结构化循环子句,例如 for 或 while,而不是原始循环 via-goto,后者在 1968 年左右仍然存在很多。即使是全能的 Knuth 最终说 -

我提出的新道德可能
或许可以这样表述:“一定要去
与以下内容有关的陈述
只要程序文档解释了转换是什么,就可以接受易于理解的转换。”

其他 此处 偶尔也有同样的想法。

I'd actually dare to suggest consideration of GOTO to break out of loops in such cases:

   for (size_t x = 0; x < LIMIT && !found; ++x) {
      if (something) 
          goto found;

      else {
          ...
      }
    }

    // not found
           ...

      return;

    found:

       ...
      return;

I consider this form to be both succint and readable. It may do some good in many simple cases (say, when there is no common processing in this function, in both found/unfound cases).

And about the general frowning goto receives, I find it to be a common misinterpretation of Dijkstra's original claims: his arguments favoured structured loop clauses, as for or while, over a primitive loop-via-goto, that still had a lot of presence circa 1968. Even the almighty Knuth eventualy says -

The new morality that I propose may
perhaps be stated thus: "Certain go to
statements which arise in connection with
well-understood transformations are acceptable, provided that the program documentation explains what the transformation was."

Others here occasionaly think the same.

撞了怀 2024-08-11 08:43:51

虽然我不同意额外的其他确实会使第二个变得更加复杂,但我认为这主要是一个美观和保持标准的问题。

就我个人而言,我可能非理性地不喜欢中断和继续,所以我更有可能使用找到的变量。

可以将找到的变量添加到第一个实现中并执行此操作...

if(something)
{
   found = true;
   break;
}

另请注意,如果您想以额外变量为代价来避免变量重载问题,但仍需要简单的循环终止符,则

While I disagree that an extra else really makes the 2nd more complicated, I think it's primarily a matter of aesthetics and keeping to your standard.

Personally, I have a probably irrational dislike of breaks and continues, so I'm MUCH more likely to use the found variable.

Also, note that you CAN add the found variable to the 1st implementation and do

if(something)
{
   found = true;
   break;
}

if you want to avoid the variable overloading problem at the expense of the extra variable, but still want the simple loop terminator...

一抹淡然 2024-08-11 08:43:51

前一个示例重复了 x <; LIMIT 条件,而后者则没有。

对于前者,如果你想改变这个条件,你必须记住在两个地方做。

The former example duplicates the x < LIMIT condition, whereas the latter doesn't.

With the former, if you want to change that condition, you have to remember to do it in two places.

沐歌 2024-08-11 08:43:51

我更喜欢完全不同的:

       for (int x = 0; x < LIMIT; ++x) {
          if (something) {
              // If we found what we're looking for, process it.
              ...
              break;
          }
          ...
       }

看来你没有提到任何关于其中一个或另一个的麻烦...;-)

  • 没有重复的条件,或可读性问题
  • 没有额外的变量

I would prefer a different one altogether:

       for (int x = 0; x < LIMIT; ++x) {
          if (something) {
              // If we found what we're looking for, process it.
              ...
              break;
          }
          ...
       }

It seems you have not any trouble you mention about one or the other... ;-)

  • no duplication of condition, or readability problem
  • no additional variable
昇り龍 2024-08-11 08:43:51

我没有任何对手(-1!-1!)的引用,但我似乎记得有多个退出点(来自函数,来自循环)已被证明会导致可维护性问题(我曾经知道为英国军方编写代码的人,并且禁止这样做)。但更重要的是,正如 RichieHindle 指出的那样,拥有重复的条件是一件坏事,它强烈要求通过更改一个而不是另一个来引入错误。

如果你以后不使用这个条件,我也不会介意。既然你是,那么第二条路就是你要走的路。

I don't have any references to hand (-1! -1!), but I seem to recall that having multiple exit points (from a function, from a loop) has been shown to cause issues with maintainability (I used to know someone who wrote code for the UK military and it was Verboten to do so). But more importantly, as RichieHindle points out, having a duplicate condition is a Bad Thing, it cries out for introducing bugs by changing one and not the other.

If you weren't using the condition later, I wouldn't be bothered either way. Since you are, the second is the way to go.

野の 2024-08-11 08:43:51

这种争论以前已经在这里争论过(可能很多次),例如在这个问题中

有些人会认为代码的纯度是最重要的,他们会痛苦地抱怨你的第一个选项并不对所有情况都有相同的后置条件。

我要回答的是“废话!”。我是一个实用主义者,而不是一个纯粹主义者。我和下一位工程师一样反对太多的意大利面条代码,但我在 for 循环中看到的一些可怕的终止条件比在循环中使用几个中断要糟糕得多。

我总是会追求代码的可读性而不是“纯度”,只是因为我必须维护它。

This sort of argument has been fought out here before (probably many times) such as in this question.

There are those that will argue that purity of code is all-important and they'll complain bitterly that your first option doesn't have identical post-conditions for all cases.

What I would answer is "Twaddle!". I'm a pragmatist, not a purist. I'm as against too much spaghetti code as much as the next engineer but some of the hideous terminating conditions I've seen in for loops are far worse than using a couple of breaks within your loop.

I will always go for readability of code over "purity" simply because I have to maintain it.

羞稚 2024-08-11 08:43:51

这看起来像是一个 while 循环的地方。无论如何,For 循环都是在 While 循环之上的语法糖。一般规则是,如果必须跳出 For 循环,请改用 While 循环。

This looks like a place for a while loop. For loops are Syntactic Sugar on top of a While loop anyway. The general rule is that if you have to break out of a For loop, then use a While loop instead.

嗳卜坏 2024-08-11 08:43:51
package com.company;

import java.io.*;
import java.util.Scanner;

public class Main {


// "line.separator" is a system property that is a platform independent and it is one way
// of getting a newline from your environment.
private static String NEWLINE = System.getProperty("line.separator");


public static void main(String[] args) {
    // write your code here

    boolean itsdone = false;

    String userInputFileName;
    String FirstName = null;
    String LastName = null;
    String user_junk;
    String userOutputFileName;
    String outString;

    int Age = -1;
    int rint = 0;
    int myMAX = 100;
    int MyArr2[] = new int[myMAX];
    int itemCount = 0;
    double average = 0;
    double total = 0;
    boolean ageDone = false;


    Scanner inScan = new Scanner(System.in);

    System.out.println("Enter First Name");

    FirstName = inScan.next();

    System.out.println("Enter Last Name");

    LastName = inScan.next();


    ageDone = false;
    while (!ageDone) {
        System.out.println("Enter Your Age");
        if (inScan.hasNextInt()) {
            Age = inScan.nextInt();
            System.out.println(FirstName + " " + LastName + " " + "is " + Age + " Years old");
            ageDone = true;
        } else {
            System.out.println("Your Age Needs to Have an Integer Value... Enter an Integer Value");
            user_junk = inScan.next();
            ageDone = false;
        }
    }

    try {
        File outputFile = new File("firstOutFile.txt");

        if (outputFile.createNewFile()){
            System.out.println("firstOutFile.txt was created"); // if file was created
        }
        else {
            System.out.println("firstOutFile.txt existed and is being overwritten."); // if file had already existed
        }

        // --------------------------------
        // If the file creation of access permissions to write into it
        // are incorrect the program throws an exception
        //

        if ((outputFile.isFile()|| outputFile.canWrite())){
            BufferedWriter fileOut = new BufferedWriter(new FileWriter(outputFile));

            fileOut.write("==================================================================");

            fileOut.write(NEWLINE + NEWLINE +" You Information is..." + NEWLINE + NEWLINE);

            fileOut.write(NEWLINE +  FirstName + " " + LastName + " " + Age + NEWLINE);

            fileOut.write("==================================================================");

            fileOut.close();

        }
        else {
            throw new IOException();
        }

    } // end of try
    catch (IOException e) { // in case for some reason the output file could not be created
        System.err.format("IOException: %s%n", e);
        e.printStackTrace();
    }
} // end main method
}
package com.company;

import java.io.*;
import java.util.Scanner;

public class Main {


// "line.separator" is a system property that is a platform independent and it is one way
// of getting a newline from your environment.
private static String NEWLINE = System.getProperty("line.separator");


public static void main(String[] args) {
    // write your code here

    boolean itsdone = false;

    String userInputFileName;
    String FirstName = null;
    String LastName = null;
    String user_junk;
    String userOutputFileName;
    String outString;

    int Age = -1;
    int rint = 0;
    int myMAX = 100;
    int MyArr2[] = new int[myMAX];
    int itemCount = 0;
    double average = 0;
    double total = 0;
    boolean ageDone = false;


    Scanner inScan = new Scanner(System.in);

    System.out.println("Enter First Name");

    FirstName = inScan.next();

    System.out.println("Enter Last Name");

    LastName = inScan.next();


    ageDone = false;
    while (!ageDone) {
        System.out.println("Enter Your Age");
        if (inScan.hasNextInt()) {
            Age = inScan.nextInt();
            System.out.println(FirstName + " " + LastName + " " + "is " + Age + " Years old");
            ageDone = true;
        } else {
            System.out.println("Your Age Needs to Have an Integer Value... Enter an Integer Value");
            user_junk = inScan.next();
            ageDone = false;
        }
    }

    try {
        File outputFile = new File("firstOutFile.txt");

        if (outputFile.createNewFile()){
            System.out.println("firstOutFile.txt was created"); // if file was created
        }
        else {
            System.out.println("firstOutFile.txt existed and is being overwritten."); // if file had already existed
        }

        // --------------------------------
        // If the file creation of access permissions to write into it
        // are incorrect the program throws an exception
        //

        if ((outputFile.isFile()|| outputFile.canWrite())){
            BufferedWriter fileOut = new BufferedWriter(new FileWriter(outputFile));

            fileOut.write("==================================================================");

            fileOut.write(NEWLINE + NEWLINE +" You Information is..." + NEWLINE + NEWLINE);

            fileOut.write(NEWLINE +  FirstName + " " + LastName + " " + Age + NEWLINE);

            fileOut.write("==================================================================");

            fileOut.close();

        }
        else {
            throw new IOException();
        }

    } // end of try
    catch (IOException e) { // in case for some reason the output file could not be created
        System.err.format("IOException: %s%n", e);
        e.printStackTrace();
    }
} // end main method
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文